package com.cocodin.barcodescan.plugin;

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

import com.rscja.deviceapi.Barcode2D;
import com.rscja.deviceapi.exception.ConfigurationException;
import com.rscja.utility.StringUtility;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class PluginHelper {

    private static final String TAG = "PluginHelper";
    private static boolean threadStop = true;
    private static String init_barcode;
    private static ExecutorService executor;
    private static Barcode2D mInstance;
    private static Handler handler;

    public static void scan(CordovaInterface cordova, CordovaWebView webView, JSONArray args,
            final CallbackContext callbackContext) {

        try {
            mInstance = Barcode2D.getInstance();

        } catch (ConfigurationException e) {
            Log.e(TAG, e.getMessage());
            return;
        }

        boolean bContinuous = false;
        Log.i("ErDActivity", "scan() ");

        executor = Executors.newFixedThreadPool(6);

        if (threadStop) {

            int iBetween = 0;

            // thread = new Thread(new GetBarcode(bContinuous, iBetween));
            // thread.start();

            executor.execute(new GetBarcode(bContinuous, iBetween));

        } else {
            threadStop = true;
        }
    }

    private static class GetBarcode implements Runnable {

        private boolean isContinuous = false;
        String barCode = "";
        private long sleepTime = 1000;
        Message msg = null;

        public GetBarcode(boolean isContinuous) {
            this.isContinuous = isContinuous;
        }

        public GetBarcode(boolean isContinuous, int sleep) {
            this.isContinuous = isContinuous;
            this.sleepTime = sleep;
        }

        @Override
        public void run() {

            do {
                barCode = mInstance.scan();

                Log.i("MY", "barCode " + barCode.trim());

                msg = new Message();

                if (StringUtility.isEmpty(barCode)) {
                    msg.arg1 = 0;
                    msg.obj = "";

                } else {

                    msg.arg1 = 1;

                    msg.obj = barCode;
                }

                handler.sendMessage(msg);

                if (isContinuous) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } while (isContinuous && !threadStop);

        }

    }
}
