package chaoran.business.service;

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

import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;

import java.util.ArrayList;

public class ScanServiceZEBRA extends Service implements EMDKManager.EMDKListener, Scanner.DataListener, Scanner.StatusListener {
    private final String TAG = "ScanService";

    private NotificationManager notificationManager;
    private String notificationId = "ScanServiceId";
    private String notificationName = "ScanServiceName";

    private EMDKManager emdkManager = null;
    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;

    private String statusString = "";

    private boolean bSoftTriggerSelected = 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) { //适配8.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);
        }
        EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.pda.scan.trigger");
        registerReceiver(myCodeReceiver, intentFilter);
    }
    private MyCodeReceiver myCodeReceiver = new MyCodeReceiver();

    public class MyCodeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int keyCode = intent.getIntExtra("data",0);
            if(keyCode == 103 || keyCode == 10036){
                if(bSoftTriggerSelected){
                    bSoftTriggerSelected = false;
                }else{
                    bSoftTriggerSelected = true;
                    cancelRead();
                }
            }
        }
    }
   /* private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle("连续扫描服务")
                .setContentText("正在运行");
        builder.setChannelId(notificationId);
        Notification notification = builder.build();
        return notification;
    }*/

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

        //setconfig();
        initScanner();
        return super.onStartCommand(intent, flags, startId);
    }
    public void setconfig(){
        Intent i = new Intent();
        i.setAction("com.symbol.datawedge.api.ACTION");
        i.putExtra("com.symbol.datawedge.api.SET_DEFAULT_PROFILE", "myProfile");
        sendBroadcast(i);
    }
    @Override
    public void onOpened(EMDKManager emdkManager) {
        updateStatus("EMDK open success!");
        this.emdkManager = emdkManager;
        // Acquire the barcode manager resources
        initBarcodeManager();
        // Enumerate scanner devices
       // enumerateScannerDevices();
        initScanner();
    }

    @Override
    public void onClosed() {
        // Release all the resources
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
        updateStatus("EMDK closed unexpectedly! Please close and restart the application.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Release all the resources
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }

    }

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
            ArrayList<ScanDataCollection.ScanData> scanData = scanDataCollection.getScanData();
            for (ScanDataCollection.ScanData data : scanData) {
                updateData(data.getData());
            }
        }
    }

    @Override
    public void onStatus(StatusData statusData) {
        StatusData.ScannerStates state = statusData.getState();
        switch (state) {
            case IDLE:
                statusString = statusData.getFriendlyName() + " is enabled and idle...";
                updateStatus(statusString);
                // set trigger type
                if(bSoftTriggerSelected) {
                    scanner.triggerType = Scanner.TriggerType.SOFT_ALWAYS;
                    setDecoders();
                } else {
                    scanner.triggerType = Scanner.TriggerType.HARD;
                    cancelRead();
                }
                // submit read
                if (!scanner.isReadPending()) {
                    try {
                        Thread.sleep(1000);
                        Log.i("jqtest:", "scan");
                        scanner.read();
                    } catch (Exception e) {
                        e.printStackTrace();
                        updateStatus(e.getMessage());
                        try {
                            deInitScanner();
                            Thread.sleep(200);
                        }catch (Exception e1){
                            e1.printStackTrace();
                        }
                        initScanner();
                    }
                }
                break;
            case WAITING:
                statusString = "Scanner is waiting for trigger press...";
                updateStatus(statusString);
                break;
            case SCANNING:
                statusString = "Scanning...";
                updateStatus(statusString);
                break;
            case DISABLED:
                statusString = statusData.getFriendlyName() + " is disabled.";
                updateStatus(statusString);
                break;
            case ERROR:
                statusString = "An error has occurred.";
                updateStatus(statusString);
                break;
            default:
                break;
        }
    }


    private void initScanner() {
        if (scanner == null) {
            if (barcodeManager != null) {
                scanner = barcodeManager.getDevice(BarcodeManager.DeviceIdentifier.DEFAULT);
            } else {
                updateStatus("Failed to get the specified scanner device! Please close and restart the application.");
                return;
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    updateStatus(e.getMessage());
                    deInitScanner();
                }
            } else {
                updateStatus("Failed to initialize the scanner device.");
            }
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.disable();
            } catch (Exception e) {
                updateStatus(e.getMessage());
            }

            try {
                scanner.removeDataListener(this);
                scanner.removeStatusListener(this);
            } catch (Exception e) {
                updateStatus(e.getMessage());
            }

            try {
                scanner.release();
            } catch (Exception e) {
                updateStatus(e.getMessage());
            }
            scanner = null;
        }
    }

    private void initBarcodeManager() {
        barcodeManager = (BarcodeManager) emdkManager.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);

    }

    private void deInitBarcodeManager() {
        if (emdkManager != null) {
            emdkManager.release(EMDKManager.FEATURE_TYPE.BARCODE);
        }
    }


/*    private void enumerateScannerDevices() {
        if (barcodeManager != null) {
            List<ScannerInfo> deviceList = barcodeManager.getSupportedDevicesInfo();
            if ((deviceList != null) && (deviceList.size() != 0)) {
                Iterator<ScannerInfo> it = deviceList.iterator();
                while (it.hasNext()) {
                    ScannerInfo scnInfo = it.next();
                    if (scnInfo.isDefaultScanner()) {
                        scannerInfo = scnInfo;
                        Log.i("scannerInfo", scannerInfo.getFriendlyName());
                        break;
                    }
                }
            }
        }
    }*/

    private void setDecoders() {
        if (scanner != null) {
            try {
                ScannerConfig config = scanner.getConfig();
                // Set EAN8
                config.decoderParams.ean8.enabled = true;
                // Set EAN13
                config.decoderParams.ean13.enabled = true;
                // Set Code39
                config.decoderParams.code39.enabled = true;
                //Set Code128
                config.decoderParams.code128.enabled = true;
//                config.readerParams.readerSpecific.imagerSpecific.aimType = ScannerConfig.AimType.PRESENTATION;
                scanner.setConfig(config);
            } catch (ScannerException e) {
            }
        }
    }

    private void cancelRead() {
        if (scanner != null) {
            if (scanner.isReadPending()) {
                try {
                    scanner.cancelRead();
                } catch (ScannerException e) {
                    updateStatus(e.getMessage());
                }
            }
        }
    }

    private void updateStatus(final String status) {
        //Log.i("status",status);
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                textViewStatus.setText("" + status);
//            }
//        });
    }

    private void updateData(final String result) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                Intent intent2 = new Intent("com.pda.scan.result");
                intent2.putExtra("data", result);
                sendBroadcast(intent2);
                Log.i(TAG, result);
            }
        }.start();
    }
}
