package com.wireless.apa;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;

import org.apache.commons.io.FileUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class RemoteActivity extends Activity implements
		SensorEventListener {
	//private InetAddress BAddress = null;
	public Activity a = this;
	private SensorManager sensorManager;
	private Sensor accelerometer;
	String left, right, hold, ac;
	private float difference = 0, last_val = 0;
	String ac_backup;
	public Toast toast;
	public int dir = 0;
	private final int MAX_NUMBER_OF_ELEMENTS = 12;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.remote_activity);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		File folder = new File(Environment.getExternalStorageDirectory()
				+ "/WirelessRemote/");

		if (!folder.exists()) {
			copyFolder("images");
			copyFolder("properties");
		}

		PropertiesHelper.getInstance().refresh();
		
		
		ActivityHelper.dialogPort(a, false);
		ActivityHelper.dialogIp(a, false);
		
		if (Integer.parseInt(PropertiesHelper.getInstance().getProperty("FIRST_TIME")) == 0) {
			new sdActivity(this);
			
			PropertiesHelper.getInstance().setProperty("FIRST_TIME", "1");
		}

		
		ActivityHelper.setImagesAndCaptions(this, false);

		try {
			setButtonFunctionality();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


				
		sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

		if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
			// success! we have an accelerometer
			left = PropertiesHelper.getInstance().getProperty("AC_LEFT");
			right = PropertiesHelper.getInstance().getProperty("AC_RIGHT");
			accelerometer = sensorManager
					.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
			sensorManager.registerListener(this, accelerometer,
					SensorManager.SENSOR_DELAY_NORMAL);
		} else {
			// fai! we dont have an accelerometer!
		}

	}

	// onResume() register the accelerometer for listening the events
	protected void onResume() {
		super.onResume();
		sensorManager.registerListener(this, accelerometer,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	// onPause() unregister the accelerometer for stop listening the events
	protected void onPause() {
		super.onPause();
		sensorManager.unregisterListener(this);
	}

	public void copyFolder(String name) {
		// "Name" is the name of your folder!
		AssetManager assetManager = getAssets();
		String[] files = null;

		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			// Checking file on assets subfolder
			try {
				files = assetManager.list(name);
			} catch (IOException e) {
				Log.e("ERROR", "Failed to get asset file list.", e);
			}
			// Analyzing all file on assets subfolder
			for (String filename : files) {
				InputStream in = null;
				OutputStream out = null;
				// First: checking if there is already a target folder
				File folder;
				String path = null;
				if (name.equals("images")) {
					path = Environment.getExternalStorageDirectory()
							+ "/WirelessRemote/";
				}

				else {
					path = Environment.getExternalStorageDirectory()
							+ "/WirelessRemote/" + name;
				}

				folder = new File(path);

				boolean success = true;
				if (!folder.exists()) {
					success = folder.mkdir();
					;
				}
				if (success) {
					// Moving all the files on external SD
					try {
						in = assetManager.open(name + "/" + filename);
						out = new FileOutputStream(path + "/" + filename);
						Log.i("WEBVIEW", path + "/" + filename);
						copyFile(in, out);
						in.close();
						in = null;
						out.flush();
						out.close();
						out = null;
					} catch (IOException e) {
						Log.e("ERROR",
								"Failed to copy asset file: " + filename, e);
					}
				} else {
					// Do something else on failure
				}
			}
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// is to know is we can neither read nor write
		}
	}

	// Method used by copyAssets() on purpose to copy a file.
	public void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}

//	InetAddress getBroadcastAddress() throws IOException {
//		WifiManager wifi = (WifiManager) this
//				.getSystemService(Context.WIFI_SERVICE);
//		DhcpInfo dhcp = wifi.getDhcpInfo();
//		// handle null somehow
//
//		int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
//		byte[] quads = new byte[4];
//		for (int k = 0; k < 4; k++)
//			quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
//		return InetAddress.getByAddress(quads);
//	}

	public void setButtonFunctionality() throws Exception {

		ImageButton selImageButton = null;
		TextView selText = null;

		for (int i = 1; i <= MAX_NUMBER_OF_ELEMENTS; i++) {
			String finalSufix = ActivityHelper.getFormattedId(i);

			String[] params = { ActivityHelper.IMAGEBUTTON_ID_ROOT, finalSufix };

			selImageButton = (ImageButton) findViewById(R.id.class
					.getDeclaredField(
							ActivityHelper.IMAGEBUTTON_ID_ROOT + finalSufix)
					.getInt(null));
			selImageButton.setTag(params);

			selText = (TextView) findViewById(R.id.class.getDeclaredField(
					ActivityHelper.TEXT_VIEW_ID_ROOT + finalSufix).getInt(null));

			if (PropertiesHelper
					.getInstance()
					.getProperty(
							ActivityHelper.IMAGEBUTTON_ID_ROOT + finalSufix
									+ ActivityHelper.DOT_TITLE)
					.contains(ActivityHelper.DISABLED)) {
				selImageButton = (ImageButton) findViewById(R.id.class
						.getDeclaredField(
								ActivityHelper.IMAGEBUTTON_ID_ROOT + finalSufix)
						.getInt(null));
				
			} else {

				selImageButton.setOnClickListener(new OnClickListener() {

					public void onClick(View arg0) {

						String[] params = (String[]) arg0.getTag();
						ImageButton b = null;
						TextView t = null;

						try {
							b = (ImageButton) arg0.findViewById(R.id.class
									.getDeclaredField(params[0] + params[1])
									.getInt(null));
							
							t = (TextView) findViewById(R.id.class
									.getDeclaredField(
											ActivityHelper.TEXT_VIEW_ID_ROOT
													+ params[1]).getInt(null));
							emitMessage(t.getText().toString());
							b.setColorFilter(null);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} // end onClick

				}); // end OnClickListener

				selImageButton
						.setOnLongClickListener(new OnLongClickListener() {

							public boolean onLongClick(View arg0) {
								String[] params = (String[]) arg0.getTag();
								dialogSelectOption(a, params[1]);

								return true;
							} // end onClick

						}); // end OnClickListener

			} // end if
		} // end for
	} // end method

	public void emitMessage(String msg) {
		// TODO Auto-generated method stub

		try {
			//UDPHelper.emitScent(this, BAddress, msg);
			TCPHelper.emitMessage(this, msg);			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			ActivityHelper.showMessage(this,
					"Error creating UDPHelper: " + e.getMessage());
		}

	}

	public static void dialogSelectOption(Activity a, String _id) {

		// Declare final variables (to be accessed in onClick)
		final Activity finalActivity = a;
		final int id = Integer.valueOf(_id);

		try {

			AlertDialog.Builder builder = new AlertDialog.Builder(a);
			builder.setTitle("Edit button");

			TextView tv = (TextView) a.findViewById(R.id.class
					.getDeclaredField(
							ActivityHelper.TEXT_VIEW_ID_ROOT
									+ ActivityHelper.getFormattedId(id))
					.getInt(null));

			CharSequence[] items = { "Change the image", "Change the hotkeys",
					"Set Special Actions", "Return" };
			builder.setItems(items, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int item) {

					switch (item) {
					case 0:
						Intent intent = new Intent(
								Intent.ACTION_PICK,
								android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						intent.setType("image/*");
						finalActivity.startActivityForResult(intent, id);
						break;

					case 1:
						ActivityHelper.dialogText(finalActivity, id);
						break;

					case 2:
						ActivityHelper.dialogSpecial(finalActivity, id);
						break;

					
					} // end switch

				}
			}); // end onClick...

			builder.setCancelable(true);
			builder.show();

		} catch (Exception e) {
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		try {

			String id = ActivityHelper.getFormattedId(requestCode);

			if (resultCode == Activity.RESULT_OK) {

				// copy image to image directory
				String selectedImagePath = ActivityHelper.getPath(this,
						data.getData());
				File source = new File(selectedImagePath);
				File desc = new File(PropertiesHelper.getInstance()
						.getImagePath()
						+ ActivityHelper.getFileName(selectedImagePath));

				try {
					FileUtils.copyFile(source, desc);
				} catch (IOException e) {
					// ActivityHelper.showMessage(a, e.getMessage());
				}
				// change properties
				PropertiesHelper.getInstance().setProperty(
						ActivityHelper.IMAGEBUTTON_ID_ROOT + id
								+ ActivityHelper.DOT_SRC,
						ActivityHelper.getFileName(selectedImagePath));

				// Refresh image
				ImageButton btn = (ImageButton) this.findViewById(R.id.class
						.getDeclaredField(
								ActivityHelper.IMAGEBUTTON_ID_ROOT + id)
						.getInt(null));
				btn.setImageDrawable(Drawable.createFromPath(selectedImagePath));
			}

		} catch (Exception e) {
		}
	} // End of method...

	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getMenuInflater().inflate(R.menu.activity_scent_session, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.change_left:
			ActivityHelper.dialogText(a, -1);
			return true;
		case R.id.change_right:
			ActivityHelper.dialogText(a, -2);
			return true;
		case R.id.accelerometer_on:
									
			if(PropertiesHelper.getInstance().getProperty("AC").equals("OFF"))
			{
				PropertiesHelper.getInstance().setProperty("AC", "ON");
				toast = Toast.makeText(getBaseContext(), "ON", 1);
			}
			else
			{
				PropertiesHelper.getInstance().setProperty("AC", "OFF");
				toast = Toast.makeText(getBaseContext(), "OFF", 1);
			}
			
			toast.show();
			return true;
		case R.id.command_show:
			String finalSufix = ActivityHelper.getFormattedId(1);
			int visibility;
			TextView selText = null;
			try {
				selText = (TextView) findViewById(R.id.class.getDeclaredField(
						ActivityHelper.TEXT_VIEW_ID_ROOT + finalSufix).getInt(
						null));
			} catch (Exception e) {}
			
			visibility = selText.getVisibility();
			
			if(visibility == View.VISIBLE)
				selText.setVisibility(View.INVISIBLE);
			else
				selText.setVisibility(View.VISIBLE);

			for (int i = 2; i <= MAX_NUMBER_OF_ELEMENTS; i++) {
				finalSufix = ActivityHelper.getFormattedId(i);
				try {
					selText = (TextView) findViewById(R.id.class
							.getDeclaredField(
									ActivityHelper.TEXT_VIEW_ID_ROOT
											+ finalSufix).getInt(null));
				} catch (Exception e) {}
				
				if(visibility == View.VISIBLE)
					selText.setVisibility(View.INVISIBLE);
				else
					selText.setVisibility(View.VISIBLE);

			}
			return true;
		
		case R.id.change_rot:
			if(PropertiesHelper.getInstance().getProperty("DIR").equals("0"))
			{
				PropertiesHelper.getInstance().setProperty("DIR", "1");
				dir = 1;
				
			}
			else
			{
				PropertiesHelper.getInstance().setProperty("DIR", "0");
				dir = 0;
				
			}
			
			toast = Toast.makeText(getBaseContext(), "Rotation direction changed", 1);
			toast.show();
			return true;
		
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub

		ac = PropertiesHelper.getInstance().getProperty("AC");
		if(ac.equals("ON"))
		{
			hold = PropertiesHelper.getInstance().getProperty("AC_HOLD");
			
			if(hold.equals("ON"))
			{
				difference = 5;
			}
			else
			{
				difference = Math.abs(event.values[dir]) - Math.abs(last_val);
			}
				
			if ((event.values[dir] > 2.5) && (difference > 2)) {
					emitMessage(left);
			} else if ((event.values[dir] < -2.5) && (difference > 2)) {
					emitMessage(right);
			}
				
			last_val = event.values[dir];
		}	
		

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}
}

class sdActivity implements MediaScannerConnectionClient {
	public String[] allFiles;
	private String SCAN_PATH;
	public Activity _a;
	private static final String FILE_TYPE = "image/*";

	private MediaScannerConnection conn;

	/** Called when the activity is first created. */
	public sdActivity(Activity a) {

		File folder = new File(Environment.getExternalStorageDirectory()
				.toString() + "/WirelessRemote/");
		allFiles = folder.list();
		// uriAllFiles= new Uri[allFiles.length];
		for (int i = 0; i < allFiles.length; i++) {
			Log.d("all file path" + i, allFiles[i] + allFiles.length);
		}
		// Uri uri= Uri.fromFile(new
		// File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
		SCAN_PATH = Environment.getExternalStorageDirectory().toString()
				+ "/WirelessRemote/";
		Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);

		startScan(a);
	}

	public void startScan(Activity a) {

		if (conn != null) {
			conn.disconnect();
		}
		conn = new MediaScannerConnection(a, this);
		conn.connect();
		Log.d("Connected", "success" + conn);

	}

	@Override
	public void onMediaScannerConnected() {
		Log.d("onMediaScannerConnected", "success" + conn);
		for (String item : allFiles) {
			conn.scanFile(SCAN_PATH + item, FILE_TYPE);
		}

	}

	@Override
	public void onScanCompleted(String path, Uri uri) {

	}
}