package com.waytous.anticollision.ui.home

import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.SerialInputOutputManager
import com.waytous.anticollision.serial.CustomProbe

class HomeRepository(
    private val usbManager: UsbManager,
    val withIoManager: Boolean
): SerialInputOutputManager.Listener{

    private lateinit var usbIoManager: SerialInputOutputManager

    private var usbPermission: UsbPermission = UsbPermission.Unknown

    private var connected:Boolean = false

    enum class UsbPermission{
        Unknown,
        Requested,
        Granted,
        Denied
    }

    fun connect(deviceId:Int, portNum:Int,baudRate:Int,requestUsbPermissions:()->Unit){
        var device : UsbDevice?=
            usbManager.deviceList.values.find { it.deviceId == deviceId } ?: return
        var driver = UsbSerialProber.getDefaultProber().probeDevice(device)
        if (driver == null) {
            driver = CustomProbe.getCustomProbe().probeDevice(device)
        }
        if (driver == null) {
            return
        }
        if (driver.ports.size < portNum) {
            return
        }
        val usbSerialPort = driver.ports[portNum]
        val usbConnection = usbManager.openDevice(driver.device)
        if (usbConnection == null && usbPermission == UsbPermission.Unknown && !usbManager.hasPermission(
                driver.device
            )
        ) {
            usbPermission = UsbPermission.Requested
            requestUsbPermissions()
            return
        }

        try {
            usbSerialPort.open(usbConnection)
            usbSerialPort.setParameters(baudRate, 8, 1, UsbSerialPort.PARITY_NONE)
            if (withIoManager) {
                usbIoManager = SerialInputOutputManager(usbSerialPort, this)
                usbIoManager.start()
            }
            connected = true
        } catch (e: Exception) {
            disconnect()
        }
    }

    private fun disconnect() {

    }

    override fun onNewData(data: ByteArray?) {
        TODO("Not yet implemented")
    }

    override fun onRunError(e: java.lang.Exception?) {
        TODO("Not yet implemented")
    }
}