package com.siwei.recyclebox.deviceUtils;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.util.Log;
import android.widget.Toast;

import com.aliyuncs.exceptions.ClientException;
import com.hoho.android.usbserial.driver.Ch34xSerialDriver;
import com.hoho.android.usbserial.driver.ProlificSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;


import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * 串口读写工具。
 */
public class SerialPortUtil {
    private Context mContext;


    private static final String TAG = "SerialPortUtil";
    private static final String INTENT_ACTION_GRANT_USB = "com.siwei.recyclebox.GRANT_USB";

    private SerialPortUtil() {
    }

    private static SerialPortUtil instance;

    public static SerialPortUtil getInstance() {
        if (instance == null) {
            instance = new SerialPortUtil();
        }
        return instance;
    }

    private UsbManager mUsbManager;
    private List<UsbSerialPort> availablePorts = new ArrayList<>();

    private List<BaseDeviceEntity> deviceList = new ArrayList<>();

    public void init(Context context) {
        mContext = context;
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        boolean addWeight = true;
        boolean addOther = true;
        boolean addUltasonic = true;

        final List<UsbSerialDriver> drivers =
                UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
        Log.i("drivers=====", drivers.toString());

        for (final UsbSerialDriver driver : drivers) {
            System.out.println("SerialPortUtil:" + driver.toString());
            System.out.println("device:" + driver.getDevice().toString());
            UsbSerialPort port = driver.getPorts().get(0);
            if (driver instanceof Ch34xSerialDriver) {
                BaseDeviceEntity weightDevice = isWeightDevice(driver);
                if (weightDevice != null && addWeight) {
                    addWeight = false;
                    SPUtils.getInstance().put("RunningState", 1);
                    Log.i(TAG, "添加称重设备");
                    deviceList.add(weightDevice);
                    continue;
                }
//               else{
//                   try {
//                       SPUtils.getInstance().put("RunningState","1");
//                       WarnActivity.SendSmsResponse("称重设备未检测到");
//                   } catch (ClientException ex) {
//                       ex.printStackTrace();
//                   }
//               }
                BaseDeviceEntity otherDevicde = isOtherDevice(driver);
                if (otherDevicde != null && addOther) {
                    addOther = false;
                    System.out.println("是otherDevice");
                    Log.i(TAG, "添加其他设备");

                    deviceList.add(otherDevicde);
//                   SerialPortUtil.getInstance().getOtherDevice().setPower();//设置电量阈值
                    continue;
                }

                BaseDeviceEntity ultrasonicDevice = isultrasonicDevice(driver);
                if (ultrasonicDevice != null && addUltasonic) {
                    addUltasonic = false;
                    deviceList.add(ultrasonicDevice);
                    Log.i(TAG, "添加超声波设备");
                    continue;
                }
//               else {
//                   try {
//                       WarnActivity.SendSmsResponse("杆、门磁、锁、、红外、超声波设备未检测到");
//                   } catch (ClientException ex) {
//                       ex.printStackTrace();
//                   }
//               }


//               deviceList.add(new PushRodDevice(mUsbManager,driver));
//               deviceList.add(new WeightDevice(mUsbManager,driver));
            } else if (driver instanceof ProlificSerialDriver) {
                deviceList.add(new RelayControllerDevice(mUsbManager, driver));
            }
/*
            final List<UsbSerialPort> ports = driver.getPorts();
            UsbDevice device= driver.getDevice();
            System.err.println("deviceDescribeContent:"+device.describeContents()+"===deviceName:"+device.getDeviceName()+"  device.toString"+device.toString());
            Log.d(TAG, String.format("+ %s: %s port%s",
                    driver, Integer.valueOf(ports.size()), ports.size() == 1 ? "" : "s"));
            for(UsbSerialPort usbSerialPort : ports){
                Log.d(TAG,"usbSerialPort:"+usbSerialPort.toString());
            }
            if(driver instanceof ProlificSerialDriver){//继电器的232接口的驱动
                availablePorts.add(ports.get(0));
            }
            if(driver instanceof Ch34xSerialDriver){        //称重的485接口的驱动。
                availablePorts.add(ports.get(0));
            }*/
        }
        BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(INTENT_ACTION_GRANT_USB)) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        System.out.println("granted extra permission");
//                        writeAndReadPort(port);

                    } else {
                        System.out.println("usbPermission denied");
                        Toast.makeText(context, "USB permission denied", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
        mContext.registerReceiver(mUsbReceiver, new IntentFilter(INTENT_ACTION_GRANT_USB));

        System.out.println("ports size:" + availablePorts.size());
        if (availablePorts.size() == 0) {
            Log.e(TAG, "没有RS232 或 RS485 设备");
            return;
        }
        PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(context, 12, new Intent(INTENT_ACTION_GRANT_USB), 0);
        for (UsbSerialPort port : availablePorts) {
            if (!mUsbManager.hasPermission(port.getDriver().getDevice())) {
                mUsbManager.requestPermission(port.getDriver().getDevice(), usbPermissionIntent);
            }
        }
    }


    public WeightDevice getWeightDevice() {
        for (BaseDeviceEntity deviceEntity : deviceList) {
            if (deviceEntity instanceof WeightDevice)//用来测试一个对象是否为一个类的实例
                return (WeightDevice) deviceEntity;
        }
        return null;
    }

    public PushRodDevice getPushRodDevice() {
        for (BaseDeviceEntity deviceEntity : deviceList) {
            if (deviceEntity instanceof PushRodDevice) {
                return (PushRodDevice) deviceEntity;
            }

        }
        return null;
    }

    //超声波
    public UltrasonicDevice getUltrasonicDevice() {
        for (BaseDeviceEntity deviceEntity : deviceList) {
            Log.i(TAG, "getUltrasonicDevice: " + deviceEntity);
            if (deviceEntity instanceof UltrasonicDevice) {
                return (UltrasonicDevice) deviceEntity;
            }

        }
        return null;
    }


    public RelayControllerDevice getRelayControllerDevive() {
        for (BaseDeviceEntity deviceEntity : deviceList) {
            if (deviceEntity instanceof RelayControllerDevice) {
                return (RelayControllerDevice) deviceEntity;
            }
        }
        return null;
    }

    public OtherDevice getOtherDevice() {
        for (BaseDeviceEntity deviceEntity : deviceList) {
            if (deviceEntity instanceof OtherDevice) {
                return (OtherDevice) deviceEntity;
            }
        }
        return null;
    }


    private BaseDeviceEntity isOtherDevice(UsbSerialDriver driver) {
        OtherDevice otherDevice = new OtherDevice(mUsbManager, driver);
        Integer infrared = otherDevice.openLock();
//        Integer  magDoor = otherDevice.queryMagDoor();
        Log.i("otherDevice", "---------------------------------------");
        if (infrared == 0) {
            otherDevice.close();
            Log.i("otherDevice", "==null");
            return null;
        }
//        if(magDoor == 3) {
//            otherDevice.close();
//            Log.i("otherDevice","==null");
//            return null;
//        }
        return otherDevice;
    }

    //超声波
    private BaseDeviceEntity isultrasonicDevice(UsbSerialDriver driver) {
        UltrasonicDevice ultrasonicDevice = new UltrasonicDevice(mUsbManager, driver);
        Integer infrared = ultrasonicDevice.ultRead();
        if (infrared == 0) {
            ultrasonicDevice.close();
            return null;
        }
//        if(magDoor == 3) {
//            otherDevice.close();
//            Log.i("otherDevice","==null");
//            return null;
//        }
        return ultrasonicDevice;
    }

    private BaseDeviceEntity isWeightDevice(UsbSerialDriver driver) {
        WeightDevice weightDevice = new WeightDevice(mUsbManager, driver);
        Integer weight = weightDevice.readIsWeight();
        Log.i("weightDevice", "---------------------------------------");
        if (weight == 1) {
            Log.i("weightDevice", "==NULL");
            weightDevice.close();
            return null;
        }
        return weightDevice;
    }

}
