package chaoran.business.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.BarcodeDeviceConnectionEvent;
import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.BarcodeReaderInfo;
import com.honeywell.aidc.ScannerNotClaimedException;
import com.honeywell.aidc.ScannerUnavailableException;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.honeywell.aidc.UnsupportedPropertyException;

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


public class ScanServiceEDA50P extends Service
        implements BarcodeReader.BarcodeListener, BarcodeReader.TriggerListener, AidcManager.BarcodeDeviceListener{
    private final String TAG = "TestScanService";

    private NotificationManager notificationManager;
    private String notificationId = "channelId";
    private String notificationName = "channelName";

    private String _Suffix = "\n";


    private AidcManager mAidcManager;
    private BarcodeReader mBarcodeReader;
    private BarcodeReader mInternalScannerReader;
    private boolean mKeyPressed = false;
    private boolean isContinue = true;

    //必须要实现的方法
    @Override
    public IBinder onBind(Intent intent) {
      //  Log.i(TAG, "onBind方法被调用!");
        return null;
    }

    //Service被创建时调用
    @Override
    public void onCreate() {
       // Log.i(TAG, "onCreate方法被调用!");
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { //适配9.0service
//        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { //适配9.0service
            channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(getApplicationContext(), notificationId).build();
            //startForeground(1,getNotification());
            startForeground(1, notification);
        }

        AidcManager.create(this, new MyCreatedCallback());
    }

    //Service被启动时调用
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand方法被调用!");
        return super.onStartCommand(intent, flags, startId);
    }

    //Service被关闭之前回调
    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy方法被调用!");
        super.onDestroy();
        if (mBarcodeReader != null) {
            mBarcodeReader.release();
        }
        if (this.mInternalScannerReader != null) {
            this.mInternalScannerReader.removeBarcodeListener(this);
            this.mInternalScannerReader.removeTriggerListener(this);
            this.mInternalScannerReader.close();
            this.mInternalScannerReader = null;
            Log.d(TAG, "Close internal scanner");
        }
        if (this.mAidcManager != null) {
            this.mAidcManager.removeBarcodeDeviceListener(this);
            this.mAidcManager.close();
        }

    }
    class MyCreatedCallback implements AidcManager.CreatedCallback {
        MyCreatedCallback() {
        }

        @Override
        public void onCreated(AidcManager aidcManager) {
            Log.d(TAG, "MyCreatedCallback onCreate !!!");
            mAidcManager = aidcManager;
            mAidcManager.addBarcodeDeviceListener(ScanServiceEDA50P.this);
            initAllBarcodeReaderAndSetDefault();
        }
    }
    void initAllBarcodeReaderAndSetDefault() {
        List<BarcodeReaderInfo> readerList = mAidcManager.listBarcodeDevices();
        Log.d(TAG, "initAllBarcodeReaderAndSetDefault readerList = "+readerList);
        mInternalScannerReader = null;
        for (BarcodeReaderInfo reader : readerList) {
            if ("dcs.scanner.imager".equals(reader.getName())) {
                mInternalScannerReader = initBarcodeReader(mInternalScannerReader, reader.getName());
            }
        }
        Log.d(TAG, "initAllBarcodeReaderAndSetDefault mInternalScannerReader = "+mInternalScannerReader);

        if (mInternalScannerReader != null) {
            mBarcodeReader = mInternalScannerReader;
        }
        else {
            Log.d(TAG, "No reader find");
        }
        if (mBarcodeReader != null) {
            try {
                mBarcodeReader.addBarcodeListener(this);
                mBarcodeReader.addTriggerListener(this);
            }
            catch (Throwable e2) {
                e2.printStackTrace();
            }
            try {
                mBarcodeReader.setProperty(BarcodeReader.PROPERTY_NOTIFICATION_GOOD_READ_ENABLED, true);
                mBarcodeReader.setProperty(BarcodeReader.PROPERTY_EAN_13_CHECK_DIGIT_TRANSMIT_ENABLED, true);

            } catch (UnsupportedPropertyException e) {
                e.printStackTrace();
            }

        }
    }

    BarcodeReader initBarcodeReader(BarcodeReader mReader, String mReaderName) {
        if (mReader == null) {
            try {
                if (mReaderName == null) {
                    mReader = mAidcManager.createBarcodeReader();
                } else {
                    mReader = mAidcManager.createBarcodeReader(mReaderName);
                }
            }
            catch (Exception e) {
                Log.e(TAG, "error", e);
            }
            try {
                mReader.claim();
                Log.d(TAG, "Call DCS interface claim() " + mReaderName);
            } catch (ScannerUnavailableException e) {
                e.printStackTrace();
            }
            try {
                mReader.setProperty(BarcodeReader.PROPERTY_TRIGGER_CONTROL_MODE, BarcodeReader.TRIGGER_CONTROL_MODE_CLIENT_CONTROL);
                mReader.setProperty(BarcodeReader.PROPERTY_DATA_PROCESSOR_LAUNCH_EZ_CONFIG, false);
                mReader.setProperty(BarcodeReader.PROPERTY_TRIGGER_AUTO_MODE_TIMEOUT, 300);

            } catch (UnsupportedPropertyException e2) {
                e2.printStackTrace();
            }
        }
        return mReader;
    }

    public void onBarcodeDeviceConnectionEvent(BarcodeDeviceConnectionEvent event) {
        Log.d(TAG, event.getBarcodeReaderInfo() + " Connection status: " + event.getConnectionStatus());
    }

    public void onBarcodeEvent(final BarcodeReadEvent event) {
        String barcodeDate = new String(event.getBarcodeData().getBytes(event.getCharset()));
        Intent intent2 = new Intent("com.honeywell.scan.broadcast");
        intent2.putExtra("data",barcodeDate);
        sendBroadcast(intent2);
        if(isContinue) {
            executorService.execute(new MyThread(mBarcodeReader));
        }
    }
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    class MyThread implements Runnable{
        private BarcodeReader mBarcodeReader;
        public MyThread(BarcodeReader mBarcodeReader){
            this.mBarcodeReader = mBarcodeReader;
        }
        @Override
        public void run() {
            {
                try {
                    Thread.sleep(1000);
                    mBarcodeReader.decode(true);
                } catch (ScannerNotClaimedException e) {
                    Log.e(TAG, "catch ScannerNotClaimedException",e);
                    e.printStackTrace();
                } catch (ScannerUnavailableException e2) {
                    Log.e(TAG, "catch ScannerUnavailableException",e2);
                    e2.printStackTrace();
                } catch (Exception e3) {
                    e3.printStackTrace();
                }

            }
        }
    }
    public void onFailureEvent(final BarcodeFailureEvent event) {
        //Log.d(TAG, "Enter onFailureEvent ===> " + event.getTimestamp());
        if(isContinue) {
            try {
                Thread.sleep(200);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
  //          doScan(true);
        }
    }

    public void onTriggerEvent(TriggerStateChangeEvent event) {
        if (event.getState()) {
            if (!mKeyPressed) {
                mKeyPressed = true;
                doScan(true);
            }else{
                mKeyPressed = false;
                doScan(false);
            }
        } else {
            //mKeyPressed = false;
           // doScan(false);
        }
      //  Log.d(TAG, "OnTriggerEvent status: " + event.getState());
    }
    void doScan(boolean do_scan) {
        try {
            if (do_scan) {
           //     Log.d(TAG, "Start a new Scan!");
            } else {
       //         Log.d(TAG, "Cancel last Scan!");
            }
            mBarcodeReader.decode(do_scan);
        } catch (ScannerNotClaimedException e) {
            Log.e(TAG, "catch ScannerNotClaimedException",e);
            e.printStackTrace();
        } catch (ScannerUnavailableException e2) {
            Log.e(TAG, "catch ScannerUnavailableException",e2);
            e2.printStackTrace();
        } catch (Exception e3) {
            e3.printStackTrace();
        }
    }
}
