package com.cocodin.barcodescan.plugin;

import java.util.concurrent.ExecutorService;

import com.zebra.adc.decoder.Barcode2DWithSoft;

import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;


import com.phonegap.plugins.barcodescanner.BarcodeScanner;

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

public class PluginHelper {

    private static final String TAG = "PluginHelper";
    private static boolean threadStop = true;
    private static ExecutorService executor;
    private static Barcode2DWithSoft mInstance;
    private static boolean MQuireOn = false;
    private static BroadcastReceiver barcodeScannerBroadcastReceiver;
    private static JSONArray Devices = new JSONArray().put("camera").put("c4050").put("NQuire300");
    private static CallbackContext cbContext;

    public static void scan(CordovaInterface cordova, CordovaWebView webView, JSONArray args,
                            final CallbackContext callbackContext) {
        String device = "";
        try {
            device = args.get(0).toString();
            if (device.equalsIgnoreCase(Devices.getString(1))) {
                Context context = cordova.getActivity();
                try {
                    mInstance = Barcode2DWithSoft.getInstance();
                    if (mInstance != null) {
                        mInstance.open(context);
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                    callbackContext.sendPluginResult(new PluginResult(Status.ERROR, e.getMessage()));
                }
                mInstance.setScanCallback(new Barcode2DWithSoft.ScanCallback() {
                    @Override
                    public void onScanComplete(int i, int length, byte[] data) {
                        Log.i(TAG, "onScanComplete() i=" + i);

                        if (length < 1) {
                            return;
                        }

                        String barCode = new String(data);
                        barCode = barCode.replaceAll("\u0000", "");
                        Log.i(TAG, barCode);

                        try {
                            JSONObject result = new JSONObject().put("text", barCode);
                            callbackContext.sendPluginResult(new PluginResult(Status.OK, result));
                        } catch (JSONException e) {
                            callbackContext.sendPluginResult(new PluginResult(Status.ERROR, e.getMessage()));
                        }
                    }
                });

                mInstance.scan();
            } else if (device.equalsIgnoreCase(Devices.getString(0))) {
                BarcodeScanner barcodeScanner = new BarcodeScanner();
                barcodeScanner.cordova = cordova;
                barcodeScanner.webView = webView;
                barcodeScanner.execute("scan", new JSONArray(), callbackContext);

            } else if (device.equalsIgnoreCase(Devices.getString(2))) {
              Context context = cordova.getActivity();
              cbContext = callbackContext;
              if(!MQuireOn) {
                initMquire(context);
              }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            callbackContext.sendPluginResult(new PluginResult(Status.ERROR, ""));
        }
    }

    public static void getDevices(CordovaInterface cordova, CordovaWebView webView, JSONArray args,
            final CallbackContext callbackContext) {
      callbackContext.sendPluginResult(new PluginResult(Status.OK, Devices));
    }

    public static void initMquire(Context context) {
      Intent intent = new Intent("ACTION_BAR_SCANCFG");
      intent.putExtra("EXTRA_SCAN_MODE", 3);
      intent.putExtra("EXTRA_SCAN_AUTOENT", 0);
      intent.putExtra("EXTRA_SCAN_NOTY_LED", 1);
      intent.putExtra("EXTRA_SCAN_NOTY_SND", 1);
      context.sendBroadcast(intent);
      MQuireOn = true;
      barcodeScannerBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
          final String scanStatus = intent.getStringExtra("SCAN_STATE");
          if (null == scanResult_1 || null == scanStatus || scanResult_1.isEmpty() || scanStatus.isEmpty()) {
            return;
          }

          if ("ok".equals(scanStatus)) {
            cbContext.success(scanResult_1);
          }
        }
      };
      context.registerReceiver(barcodeScannerBroadcastReceiver, new IntentFilter("nlscan.action.SCANNER_RESULT"));
    }
}