package com.casic.common.detector.gd.uart

import android.util.Log
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

class SerialPort(device: File, baudRate: Int, flags: Int) {

    private val kTag = "SerialPort"
    private var fd: FileDescriptor? = null
    var inputStream: InputStream
    var outputStream: OutputStream

    init {
        System.loadLibrary("serial_port")

        if (!device.canRead() || !device.canWrite()) {
            try {
                val su = Runtime.getRuntime().exec("/system/bin/su")
                val cmd = "chmod 666 ${device.absolutePath} \n exit \n"
                su.outputStream.write(cmd.toByteArray())
                if (su.waitFor() != 0 || !device.canRead() || !device.canWrite()) {
                    throw SecurityException()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                throw SecurityException()
            }
        }
        fd = open(device.absolutePath, baudRate, flags)
        if (fd == null) {
            Log.e(kTag, "SerialPort open return null")
            throw IOException()
        }
        inputStream = FileInputStream(fd)
        outputStream = FileOutputStream(fd)
    }

    fun closeSerialPort() {
        close()
    }

    private external fun open(path: String, baudRate: Int, flags: Int): FileDescriptor?

    private external fun close()
}