package com.homansystem.iposprinter;

import android.content.Context;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import java.util.Set;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.app.ActivityCompat;
import java.util.HashMap;
import java.util.Collections;
import java.util.Map;
import android.app.Activity;
// import com.facebook.react.bridge.Promise;
import android.content.pm.PackageManager;
import android.app.Activity;
import com.facebook.react.bridge.*;

public class BTDiscovery implements ActivityEventListener {
  private static final int REQUEST_ENABLE_BT = 2;
  private Context mContext = null;
  private BluetoothAdapter mBtAdapter;
  private static final Map<String, Promise> promiseMap = Collections.synchronizedMap(new HashMap<String, Promise>());
  private static final String PROMISE_ENABLE_BT = "ENABLE_BT";
  private Activity mActivity;
  public BTDiscovery(final Context context,Activity activity){
    mContext = context;
    mActivity = activity;
    ReactApplicationContext reactContext = (ReactApplicationContext) context;
    reactContext.addActivityEventListener(this);
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
    if(pairedDevices.size() > 0){
      for(BluetoothDevice device : pairedDevices){
         Intent intent = new Intent("BTDeviceFound");
        intent.putExtra("PrinterName",device.getName());
        intent.putExtra("PrinterAddress",device.getAddress());
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadcastManager.sendBroadcast(intent);
      }
    }
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    context.registerReceiver(mReceiver,filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    context.registerReceiver(mReceiver,filter);
  }

  @Override
  public void onNewIntent(Intent intent){

  }

  public void startDiscovery(){
    int permissionChecked = ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION);
    if (permissionChecked == PackageManager.PERMISSION_DENIED) {
      ActivityCompat.requestPermissions(mActivity,
              new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
              1);
    }
    if(mBtAdapter != null){
      if(mBtAdapter.isDiscovering()){
        mBtAdapter.cancelDiscovery();
      }
      mBtAdapter.startDiscovery();
    }

  }

  public void stopDiscovery(){
    if(mBtAdapter != null){
      if(mBtAdapter.isDiscovering()){
        mBtAdapter.cancelDiscovery();
      }
      mContext.unregisterReceiver(mReceiver);
    }

  }

  public void isBluetoothEnabled(Promise promise){
    promise.resolve(mBtAdapter !=null && mBtAdapter.isEnabled());
  }

  public void enableBluetooth(final Promise promise) {
    if(mBtAdapter == null){
        promise.reject("Adapter Not Initialized");
    }else if (!mBtAdapter.isEnabled()) {
        Intent enableIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
        promiseMap.put(PROMISE_ENABLE_BT, promise);
        mActivity.startActivityForResult(enableIntent, REQUEST_ENABLE_BT, Bundle.EMPTY);
    } else {
        promise.resolve(null);
    }
  }

   @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
      BluetoothAdapter adapter = mBtAdapter;
      switch (requestCode) {
          case REQUEST_ENABLE_BT: {
              Promise promise = promiseMap.remove(PROMISE_ENABLE_BT);
              if (resultCode == Activity.RESULT_OK && promise != null) {
                  // Bluetooth is now enabled, so set up a session
                  if(adapter!=null){
                      promise.resolve(null);
                  }else{
                      promise.resolve(null);
                  }

              } else {
                  // User did not enable Bluetooth or an error occured
                  if (promise != null) {
                      promise.reject("ERR", new Exception("BT NOT ENABLED"));
                  }
              }
              break;
          }
      }
  }


  private final BroadcastReceiver mReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent){
      String action = intent.getAction();
      if(BluetoothDevice.ACTION_FOUND.equals(action)){
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if(device.getBondState() != BluetoothDevice.BOND_BONDED){
          Intent sendIntent = new Intent("BTDeviceFound");
          sendIntent.putExtra("PrinterName",device.getName());
          sendIntent.putExtra("PrinterAddress",device.getAddress());
          LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
          localBroadcastManager.sendBroadcast(sendIntent);
        }
      }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
        
      }
    }
  };
}