package activities;

import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TwoLineListItem;

import controllers.PinpadManager;
import controllers.PinpadManager.OnConnectionEstablishedListener;
import facade.PayPadManager;
import models.messaging.nibss.Globals;
import com.esl.lib.PaypadFacade;
import org.json.JSONObject;
import org.json.JSONException;
import org.apache.cordova.*;

public class DeviceActivity extends Activity {

	private class BluetootDevicePair {
		String name;
		String addr;
	}

//	private class BluetoothDeviceAdapter extends
//			ArrayAdapter<BluetootDevicePair> {
//		public BluetoothDeviceAdapter(Context context) {
//
//			super(context, android.R.layout.simple_list_item_2);
//
//		}
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {
//			TwoLineListItem v = (TwoLineListItem) convertView;
//
//			if (v == null) {
//				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//				v = (TwoLineListItem) inflater.inflate(
//						android.R.layout.simple_list_item_2, null);
//			}
//
//			BluetootDevicePair device = getItem(position);
//			v.getText1().setText(device.name);
//			// v.getText2().setText(device.addr);
//
//			return v;
//		}
//	}

	private PinpadManager mPinpadManager;
//	private BluetoothDeviceAdapter mListAdapter;
	private ListView mListView;
	private Handler deviceActivityHandler;

//	private ProgressDialog mProgressDialog;

	private PayPadManager Pd;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Pd = new PayPadManager(this);
        Bundle bundle = getIntent().getExtras();
        String btAddress = bundle.getString("btAddress");

		setResult(RESULT_CANCELED);

		mPinpadManager = PinpadManager.getInstance(this);
		deviceActivityHandler = new Handler();
		mPinpadManager
				.setOnConnectionEstablishedListener(new OnConnectionEstablishedListener() {
					@Override
					public void OnConnectionEstablished() {

						runOnUiThread(new Runnable() {
							public void run() {
								// set this to check if connected
								Globals.isPinpadConnected = true;

								try{
									JSONObject objR = new JSONObject();
									objR.put("operation","connection");
									objR.put("status","connected");

									PluginResult result = new PluginResult(PluginResult.Status.OK, objR);
									result.setKeepCallback(true);
									PaypadFacade.callbackContext.sendPluginResult(result);
									
								}catch(JSONException e){

								}

								showToast("Device is connected");
								setResult(RESULT_OK);
								finish();
							}
						});
					}
				});


        connectToDevice(btAddress);

//		MiscUtils.initContext(getApplicationContext());
//		String pinpadMacAddress = MiscUtils.getFromSharedPreferences(
//				ReferenceList.preference, ReferenceList.pinpadMACAddress, "");
//
//		if (pinpadMacAddress.equals("") || pinpadMacAddress == null) {
//
//			Globals.autoConnect = false;
//			showConnectPinpadDialog();
//
//		} else {
//
//			Globals.autoConnect = true;
//			btAddress = pinpadMacAddress;
//			connectToDevice(btAddress);
//		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		Pd.onActivityResult(requestCode, resultCode, data);
	}

	/** Called when the activity is destroyed. */
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

//	private void showConnectPinpadDialog() {
//		mListAdapter = new BluetoothDeviceAdapter(this);
//		mListView = (ListView) findViewById(R.id.listView);
//		mListView.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> parentView, View view,
//					int position, long id) {
//
//				Globals.autoConnect = false;
//				btAddress = mListAdapter.getItem(position).addr;
//				connectToDevice(btAddress);
//
//			}
//		});
//		mListView.setAdapter(mListAdapter);
//
//		findViewById(R.id.cancel).setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				finish();
//			}
//		});
//
//		updateDeviceList();
//	}
//
	// Show toast notification, running in UI thread.
	private void showToast(final String text) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), text,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	// Populate list with paired bluetooth devices.
//	private void updateDeviceList() {
//		BluetoothAdapter bthAdapter = BluetoothAdapter.getDefaultAdapter();
//
//		if (bthAdapter != null) {
//			for (BluetoothDevice device : bthAdapter.getBondedDevices()) {
//				BluetootDevicePair pair = new BluetootDevicePair();
//				pair.name = device.getName();
//				pair.addr = device.getAddress();
//				mListAdapter.add(pair);
//			}
//		}
//
//		mListAdapter.notifyDataSetChanged();
//	}

	// Connect to specific bluetooth device.
	private void connectToDevice(final String btAddress) {
		String dialogMessage;
		// Construct a progress dialog to prevent user from actions until
		// connection is finished.
//		final ProgressDialog dialog = new ProgressDialog(DeviceActivity.this);
//		if (Globals.autoConnect) {
//			dialogMessage = "Auto connecting pinpad";
//		} else {
//			dialogMessage = getString(R.string.msg_please_wait);
//		}
//		dialog.setMessage(dialogMessage);
//		dialog.setCancelable(false);
//		dialog.setCanceledOnTouchOutside(false);
//		dialog.setOnKeyListener(new OnKeyListener() {
//			@Override
//			public boolean onKey(DialogInterface dialog, int keyCode,
//					KeyEvent event) {
//				return true;
//			}
//		});
//		dialog.show();

		// Force connection to be execute in separate thread.
		final Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					mPinpadManager.connect(btAddress);

				} catch (IOException e) {
					e.printStackTrace();
					showToast("Device is not connected");
					Globals.isPinpadConnected = false;
					try{
						JSONObject objR = new JSONObject();
						objR.put("operation","connection");
						objR.put("status","failed");

						PluginResult result = new PluginResult(PluginResult.Status.ERROR, objR);
						result.setKeepCallback(true);
						PaypadFacade.callbackContext.sendPluginResult(result);
						
					}catch(JSONException ex){

					}
//					if (Globals.autoConnect) { // show dialog after auto
//												// connecting failed
//						deviceActivityHandler.post(new Runnable() {
//							@Override
//							public void run() {
//								Globals.autoConnect = false;
//								showConnectPinpadDialog();
//							}
//						});
//
//					}
				} finally {
					//dialog.dismiss();
				}
			}
		});
		t.start();

	}
	

}
