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 org.json.JSONObject;
import org.json.JSONException;
import android.app.IntentService;
import com.esl.lib.PaypadFacade;
import org.apache.cordova.*;
import models.messaging.nibss.Globals;
import facade.PayPadManager;

public class DeviceActivityS extends IntentService  {

	private PinpadManager mPinpadManager;
//	private BluetoothDeviceAdapter mListAdapter;
	private ListView mListView;
	private Handler deviceActivityHandler;
	private Intent intent1;

//	private ProgressDialog mProgressDialog;
	private PayPadManager Pd;

    public DeviceActivityS(){
        super("Device ActivityS");
    }
	/** Called when the activity is destroyed. */
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

    @Override
    protected void onHandleIntent(Intent intent) {

    	intent1 = intent1;
        Pd = new PayPadManager(this);
        Bundle bundle = intent.getExtras();
        String btAddress = bundle.getString("btAddress");

        // showToast("BT "+ btAddress);
        mPinpadManager = PinpadManager.getInstance(this);

        mPinpadManager
                .setOnConnectionEstablishedListener(new PinpadManager.OnConnectionEstablishedListener() {
                    @Override
                    public void OnConnectionEstablished() {

                        // ((Activity)PaypadFacade.activityContext).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);

                                    // showToast("sending back result");

                                    Pd.onActivityResult(PayPadManager.REQUEST_DEVICE,-1,intent1);

                                }catch(Exception e){
                                	// showToast("Error : "+e.getMessage());
                                	PluginResult result = new PluginResult(PluginResult.Status.ERROR, "Error: "+e.getMessage());
                                    // result.setKeepCallback(true);
                                    PaypadFacade.callbackContext.sendPluginResult(result);
                                }

                        //         showToast("Device is connected");
                        //     }
                        // });
                    }
                });


        connectToDevice(btAddress);
    }

	// Show toast notification, running in UI thread.
	private void showToast(final String text) {
		((Activity)PaypadFacade.activityContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(PaypadFacade.activityContext, text,
						Toast.LENGTH_SHORT).show();
			}
		});
	}
	// Connect to specific bluetooth device.
	private void connectToDevice(final String btAddress) {

		// 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){

					}
				} finally {
					//dialog.dismiss();
				}
		// 	}
		// });
		// t.start();

	}
	

}
