package com.cocodin.barcodescan.plugin;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.rscja.utility.StringUtility;
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 com.phonegap.plugins.barcodescanner.BarcodeScanner;

import android.content.Context;
import android.os.Message;
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;

    public static void init(CordovaInterface cordova) {
        Context context = cordova.getActivity();
        try {
            mInstance = Barcode2DWithSoft.getInstance();
            if (mInstance != null) {
                mInstance.open(context);
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    public static void scan(CordovaInterface cordova, CordovaWebView webView, JSONArray args,
            final CallbackContext callbackContext) {
        String device = "";
        try {
            device = args.get(0).toString();
        } catch (JSONException e) {
            e.printStackTrace();
            callbackContext.sendPluginResult(new PluginResult(Status.ERROR, ""));
        }
        if (device.equalsIgnoreCase("scanner")) {
            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) {
                        e.printStackTrace();
                        callbackContext.sendPluginResult(new PluginResult(Status.ERROR, ""));
                    }
                }
            });

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