package com.hh.lib_dx_qr;

import static android.content.Context.BIND_AUTO_CREATE;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.hh.lib_dx_qr.usbqr.UsbService;

import java.util.HashMap;
import java.util.Set;

public class QrUsb {



    volatile DxQrResultCallback resultCallBack;
    Context mContext;

    public void init(Context context, DxQrResultCallback resultCallBack) {
        this.mContext = context;
        this.resultCallBack = resultCallBack;

//        Common.e("USB-init");
     //   Log.e("____________123", "USB-init");

        //二维码
        mHandler = new MyHandler();

        setFilters();  //从UsbService开始监听通知
        startService(UsbService.class, usbConnection, null); //   启动UsbService(如果它之前没有启动)并绑定它

        OpenUSB();

    }


    private void setFilters() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
        filter.addAction(UsbService.ACTION_NO_USB);
        filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
        filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
        filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
        mContext.registerReceiver(mUsbReceiver, filter);
    }

    Intent bindingIntent;
    Intent startService;
    private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
        if (!UsbService.SERVICE_CONNECTED) {
             startService = new Intent(mContext, service);
            if (extras != null && !extras.isEmpty()) {
                Set<String> keys = extras.keySet();
                for (String key : keys) {
                    String extra = extras.getString(key);
                    startService.putExtra(key, extra);
                }
            }
            mContext.startService(startService);
        }
          bindingIntent = new Intent(mContext, service);
        mContext.bindService(bindingIntent, serviceConnection, BIND_AUTO_CREATE);
    }



    private String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"};
    private UsbManager usbManager;
    private PendingIntent mPendingIntent;
    private final String ACTION_USB_PERMISSION = "com.donsee.devices.DonseeDeviceActivity.USB_PERMISSION";
    private int pid = 57407;
    private int vid = 1742;
    private UsbDevice usbDevice;


    private void OpenUSB() {
        usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        if (Build.VERSION.SDK_INT >= 31) {
            mPendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
        } else {
            mPendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        }
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        mContext.registerReceiver(mUsbReceiver, filter);
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        if (!deviceList.isEmpty()) {
            for (UsbDevice next : deviceList.values()) {
                if (next.getVendorId() == vid && next.getProductId() == pid) {

                    usbDevice = next;
                    if (!usbManager.hasPermission(usbDevice)) {
                        usbManager.requestPermission(usbDevice, mPendingIntent);
                    }
                    return;
                }
            }
        }
       // Log.e("____________123", "------------No USB connected");
        if (resultCallBack != null) {
            resultCallBack.onInitFail(-2, "No USB connected，请检查OTG连接、USB线连接");
        }
    }


    //二维码阅读器（usb转虚拟串口通信后）
    private volatile UsbService usbService;
    private volatile MyHandler mHandler;
    private final ServiceConnection usbConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1) {
            usbService = ((UsbService.UsbBinder) arg1).getService();
            usbService.setHandler(mHandler);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            usbService = null;
        }
    };
    /*
     * 这里将收到来自UsbService的通知。
     */
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB 准备完成
                  //  Log.e("____________123", "------------USB Ready");
                    if (resultCallBack != null)
                        resultCallBack.onInitSuccess();
                    break;
                case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB 未授权
                   // Log.e("____________123", "------------USB Permission not granted");
                    if (resultCallBack != null)
                        resultCallBack.onInitFail(-1,"USB Permission not granted，请检查OTG连接、USB线连接");
                    break;
                case UsbService.ACTION_NO_USB: // 无USB连接
                  //  Log.e("____________123", "------------No USB connected");
                    if (resultCallBack != null)
                        resultCallBack.onInitFail(-2,"No USB connected，请检查OTG连接、USB线连接");
                    break;
                case UsbService.ACTION_USB_DISCONNECTED: // USB 断开
                  //  Log.e("____________123", "------------USB disconnected");
                    if (resultCallBack != null)
                        resultCallBack.onInitFail(-3,"USB disconnected，请检查OTG连接、USB线连接");
                    break;
                case UsbService.ACTION_USB_NOT_SUPPORTED: // 不支持USB
                   // Log.e("____________123", "------------USB device not supported");
                    if (resultCallBack != null)
                        resultCallBack.onInitFail(-4,"USB device not supported，请检查OTG连接、USB线连接");
                    break;
            }
        }
    };


    /*
     * 此处理程序将传递给UsbServices。通过此处理程序显示从串口接收的数据。
     */
    private class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UsbService.MESSAGE_FROM_SERIAL_PORT:
                    String data = (String) msg.obj;
                    if (data != null && !data.equals("")) {
                     //   Log.e("____________123", "二维码---数据返回:\n" + data);
                      //  Toast.makeText(mContext, "二维码---数据返回:\n" + data, Toast.LENGTH_SHORT).show();
                        if (resultCallBack != null) {
                            resultCallBack.onSuccess( data);
                        }
                    }
                    break;
                case UsbService.CTS_CHANGE:
                  //  Log.e("____________123", "CTS_CHANGE");
                    break;
                case UsbService.DSR_CHANGE:
                  //  Log.e("____________123", "DSR_CHANGE");
                    break;
            }
        }
    }




    public void onRelease() {
        resultCallBack = null;
        if (mContext != null && usbConnection != null) {
            try {
                mContext.unbindService(usbConnection);
            }catch (Exception e){

            }

        }
        if(mContext!=null&&startService!=null){
            mContext.stopService(startService);
        }
        if(mContext!=null&&mUsbReceiver!=null){
            mContext.unregisterReceiver(mUsbReceiver);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }

    }

    public interface DxQrResultCallback{
        void onSuccess(String qrCode);
        void onFail();

        void onInitSuccess();
        void onInitFail(int code,String errMsg);

    }
}
