package com.printer.sdk.usb;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Looper;
import android.util.Log;



import java.util.HashMap;

import etelligens.com.foodsafety.PrintLabel.PrintClasses.DeviceCallback;
import etelligens.com.foodsafety.PrintLabel.PrintClasses.DiscoveryCallback;


public class UsbPort {
    private static final int TIME_OUT =300 ;
    private Context context;
    private UsbManager mUsbManager;
    private UsbDevice mUsbDevice;
    private UsbDeviceConnection connection;
    private UsbInterface usbInterface;
    private UsbEndpoint inEndpoint;
    private UsbEndpoint outEndpoint;
    private final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    private static String TAG = "USBPort";


    private DeviceCallback deviceCallback;
    private DiscoveryCallback discoveryCallback;
    private USBCallback usbPortCallback;
    private boolean connected;

    public UsbPort(Context context) {
        initialize(context);
    }

    private void initialize(Context context) {
        this.context = context;
        this.deviceCallback = null;
        this.discoveryCallback = null;
        this.usbPortCallback = null;
        this.connected = false;
        mUsbManager = (UsbManager) this.context.getSystemService(Context.USB_SERVICE);
    }

    public void onStop() {
        context.unregisterReceiver(mUsbAttachReceiver);
    }

    public void enable() {

    }
    private final BroadcastReceiver mUsbAttachReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.w("yxz", "receiver action: " + action);
            if(usbPortCallback!=null)
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                usbPortCallback.onUSBTurningOn();
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                usbPortCallback.onUSBTurningOff();
                if (connected) {
                    disconnect();
                }
            }
        }
    };
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.w(TAG, "receiver action: " + action);

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    context.unregisterReceiver(mUsbReceiver);
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                            && mUsbDevice.equals(device)) {
                        new ConnectThread().start();
                    } else {
                        if (deviceCallback != null) {
                            deviceCallback.onUsbError("permission denied for device " + device);
                        }
                        Log.e(TAG, "permission denied for device " + device);
                    }
                }
            }
        }
    };

    public void connectToAddress() {
        connectToDevice();
    }


    public void connectToDevice() {
        HashMap<String, UsbDevice> devices = mUsbManager.getDeviceList();
        for (UsbDevice device : devices.values()) {
            if (isUsbPrinter(device)) {
                this.mUsbDevice = device;
                break;
            }
        }
        if (mUsbManager.hasPermission(mUsbDevice)) {
            new ConnectThread().start();
        } else {
            // 没有权限询问用户是否授予权限
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                    new Intent(ACTION_USB_PERMISSION), 0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            context.registerReceiver(mUsbReceiver, filter);
            mUsbManager.requestPermission(mUsbDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框
        }
    }

    public boolean isConnected() {
        return connected;
    }


    public void send(byte[] msg) {
        sendMessage(msg);
    }

    public void sendImage(byte[] byteArray) {
        try {
            connection.bulkTransfer(outEndpoint, byteArray, byteArray.length, 0);
            byte[]data =new byte[]{0x0b,0x0c};
            connection.bulkTransfer(outEndpoint, byteArray, byteArray.length, 100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startScanning() {
        discoveryCallback.onUsbDiscoveryStarted();
        HashMap<String, UsbDevice> devices = mUsbManager.getDeviceList();
        for (UsbDevice device : devices.values()) {
            if (isUsbPrinter(device)) {
                discoveryCallback.onUsbDeviceFound(device);
            }
        }
        discoveryCallback.onUsbDiscoveryFinished();
    }
    public void onStart() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(mUsbAttachReceiver, filter);
    }

    public boolean isEnabled() {
        return true;
    }

    public void onActivityResult(int requestCode, final int resultCode) {

    }

    public void disconnect() {
        try {
            if (connection != null) {
                connection.releaseInterface(usbInterface);
                // 只能关闭一次
                connection.close();
                connection = null;
                connected=false;
            }
        } catch (final Exception e) {
            if (deviceCallback != null)
                deviceCallback.onUsbError(e.getMessage());
        }
    }

    public void sendMessage(byte[] msg) {
        try {
            connection.bulkTransfer(outEndpoint, msg, msg.length, TIME_OUT);
        } catch (final Exception e) {
            connected = false;
            if (deviceCallback != null)
                deviceCallback.onUsbDeviceDisconnected(mUsbDevice, e.getMessage());
        }
    }

    public void setDeviceCallback(DeviceCallback deviceCallback) {
        this.deviceCallback = deviceCallback;
    }

    public void setDiscoveryCallback(DiscoveryCallback discoveryCallback) {
        this.discoveryCallback = discoveryCallback;
    }

    private class ReceiveThread extends Thread implements Runnable {
        public void run() {
            String msg;
            byte[] buffer=new byte[128];
            int readLen = -1;
            try {
                while ((readLen = connection.bulkTransfer(inEndpoint, buffer, buffer.length, TIME_OUT)) > 0) {
                    if (deviceCallback != null) {
                        byte[] buffer2=new byte[readLen];
                        System.arraycopy(buffer,0,buffer2,0,readLen);
                        buffer=new byte[128];
                        final String msgCopy = buffer2.toString();
                        new android.os.Handler(Looper.getMainLooper()).post(() -> deviceCallback.onUsbMessage(msgCopy));
                    }
                }
            } catch (final Exception e) {
                connected = false;
                if (deviceCallback != null)
                    new android.os.Handler(Looper.getMainLooper()).post(() -> deviceCallback.onUsbDeviceDisconnected(mUsbDevice, e.getMessage()));
            }
        }
    }

    public void setUsbPortCallback(USBCallback usbPortCallback) {
        this.usbPortCallback = usbPortCallback;
    }

    private class ConnectThread extends Thread {
        ConnectThread() {
            if (!isUsbPrinter(mUsbDevice)) {
                if (deviceCallback != null) {
                    deviceCallback.onUsbError("usb device is not a printer.");
                }
            }
            if (!mUsbManager.hasPermission(mUsbDevice)) {
                if (deviceCallback != null) {
                    deviceCallback.onUsbError(" usb device doesn't has permission.");
                }
            }
        }

        public void run() {
            usbInterface = mUsbDevice.getInterface(0);
            for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
                // USBEndpoint为读写数据所需的节点
                UsbEndpoint ep = usbInterface.getEndpoint(i);
                if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                    if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                        outEndpoint = ep;
                    } else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                        inEndpoint = ep;
                    }
                }
            }
            connection = mUsbManager.openDevice(mUsbDevice);
            if (connection != null && connection.claimInterface(usbInterface, true)) {
                connected = true;
                new ReceiveThread().start();
                if (deviceCallback != null)
                    new android.os.Handler(Looper.getMainLooper()).post(() -> deviceCallback.onUsbDeviceConnected(mUsbDevice));
            } else {
                if (connection != null) {
                    connection.releaseInterface(usbInterface);
                    // 只能关闭一次
                    connection.close();
                    connection = null;
                    connected=false;
                }
                if (deviceCallback != null) {
                    new android.os.Handler(Looper.getMainLooper()).post(() -> deviceCallback.onUsbConnectError(mUsbDevice, "usb device connect fail"));
                }
            }
        }
    }


    public static boolean isUsbPrinter(UsbDevice device) {
        int vendorId = device.getVendorId();
        int productId = device.getProductId();
        if ((0x0483 == vendorId && 0x5720 == productId) || (0x067B == vendorId && 0x2305 == productId)) {
            return true;
        } else {
            return false;
        }
    }
}
