package com.sparta.estimote;

import android.content.Context;
import android.util.Log;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;

import com.estimote.sdk.*;
import com.estimote.sdk.cloud.model.*;
import com.estimote.sdk.connection.*;
import com.estimote.sdk.exception.*;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class EstimoteBeacon extends CordovaPlugin {
    private BeaconManager mBeaconManager;
	private EstimoteSDK mEstimoteSDK;
    private CordovaInterface mCordovaInterface;
    
    private CallbackContext mBluetoothStateCallbackContext;
    
    private static final int REQUEST_ENABLE_BLUETOOTH = 1;
    private static final String LOGTAG = "EstimoteBeacons";
    
    private ArrayList<Beacon> mRangedBeacons;
    
    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        Log.i(LOGTAG, "initialize");

		super.initialize(cordova, webView);

		mCordovaInterface = cordova;
		mCordovaInterface.setActivityResultCallback(this);

		if (mBeaconManager == null) {
			mBeaconManager = new BeaconManager(cordova.getActivity());
		}
        
        mRangedBeacons = new ArrayList<Beacon>();
        
        mBeaconManager.setRangingListener(new BeaconManager.RangingListener() {
            @Override
            public void onBeaconsDiscovered(Region region, final List<Beacon> beaconList) {
                
                Log.i(LOGTAG, "onBeaconsDiscovered");
                mRangedBeacons.clear();
                mRangedBeacons.addAll(beaconList);
            }
        });
        
    }
    
    @Override
    public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
        if("checkbluetoothState".equals(action)){
            checkBluetoothState(args , callbackContext);
        }else{
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
            return false;
        }
        return true;
    }
    
    private void checkBluetoothState(CordovaArgs cordovaArgs,final CallbackContext callbackContext) throws JSONException {
        
        // Check that no Bluetooth state request is in progress.
		if (null != mBluetoothStateCallbackContext) {
			callbackContext.error("Bluetooth state request already in progress");
			return;
		}
        
        if (!mBeaconManager.isBluetoothEnabled()) {
			// Open Bluetooth dialog on the UI thread.
			final CordovaPlugin self = this;
			mBluetoothStateCallbackContext = callbackContext;
			Runnable openBluetoothDialog = new Runnable() {
				public void run() {
					Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
					mCordovaInterface.startActivityForResult(
						self,
						enableIntent,
						REQUEST_ENABLE_BLUETOOTH);
				}
			};
			mCordovaInterface.getActivity().runOnUiThread(openBluetoothDialog);
		}else {
            sendResultForBluetoothEnabled(callbackContext);
        }
    }
    
    /**
	 * Check if Bluetooth is enabled and return result to JavaScript.
	 */
	public void sendResultForBluetoothEnabled(CallbackContext callbackContext)
	{
		if (mBeaconManager.isBluetoothEnabled()) {
			callbackContext.success(1);
		}
		else {
			callbackContext.success(0);
		}
	}
    
    /**
	 * Called when the Bluetooth dialog is closed.
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
		Log.i(LOGTAG, "onActivityResult");
		if (REQUEST_ENABLE_BLUETOOTH == requestCode) {
			sendResultForBluetoothEnabled(mBluetoothStateCallbackContext);
			mBluetoothStateCallbackContext = null;
		}
	}
    
    @Override
    public void onPause(boolean multitasking) {
        super.onPause(multitasking);
    }

    @Override
    public void onResume(boolean multitasking) {
        super.onResume(multitasking);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}