package com.grkj.iscs.view.presenter

import android.content.Context
import android.content.Intent
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.grkj.iscs.BusinessManager
import com.grkj.iscs.R
import com.grkj.iscs.model.DeviceConst.DOCK_TYPE_COLLECT
import com.grkj.iscs.model.DeviceConst.DOCK_TYPE_ELEC_LOCK_BOARD
import com.grkj.iscs.model.DeviceConst.DOCK_TYPE_KEY
import com.grkj.iscs.model.DeviceConst.DOCK_TYPE_LOCK
import com.grkj.iscs.model.DeviceConst.DOCK_TYPE_PORTABLE
import com.grkj.iscs.util.CommonUtils
import com.grkj.iscs.util.SPUtils
import com.grkj.iscs.util.ToastUtils
import com.grkj.iscs.view.base.BasePresenter
import com.grkj.iscs.view.fragment.DockTestFragment
import com.grkj.iscs.view.fragment.SystemSettingFragment.DockItem
import com.grkj.iscs.view.iview.ISystemSettingView
import java.io.File
import kotlin.system.exitProcess

class SystemSettingPresenter : BasePresenter<ISystemSettingView>() {

    fun getDockTypeList(): MutableList<DockItem> {
        return mutableListOf(
            DockItem(mContext!!.getString(R.string.board_type_key), DOCK_TYPE_KEY),
            DockItem(mContext!!.getString(R.string.board_type_lock), DOCK_TYPE_LOCK),
            DockItem(mContext!!.getString(R.string.board_type_portal), DOCK_TYPE_PORTABLE),
            DockItem(mContext!!.getString(R.string.board_type_collect), DOCK_TYPE_COLLECT),
            DockItem(mContext!!.getString(R.string.board_type_elec_lock), DOCK_TYPE_ELEC_LOCK_BOARD)
        )
    }

    fun getDockList(): MutableList<DockTestFragment.DockTestBean> {
        val dockConfigJson = SPUtils.getDockConfig(mContext!!)
        if (!dockConfigJson.isNullOrEmpty()) {
            val tempList: MutableList<DockTestFragment.DockTestBean> =
                Gson().fromJson(
                    dockConfigJson,
                    object : TypeToken<MutableList<DockTestFragment.DockTestBean>>() {}.type
                )
            return tempList
        }
        return mutableListOf()
    }

    fun addBoard(
        address: String,
        type: Byte?,
        dockList: MutableList<DockTestFragment.DockTestBean>,
        callback: () -> Unit
    ) {
        if (type == null) {
            ToastUtils.tip(R.string.please_select_board_type)
            return
        }
        if (address.isEmpty()) {
            ToastUtils.tip(R.string.please_input_address)
            return
        }
        if (!CommonUtils.isValidHex(address)) {
            ToastUtils.tip(R.string.please_input_valid_address)
            return
        }
        dockList.add(DockTestFragment.DockTestBean(address.toInt(16).toByte(), type))
        callback()
    }

    fun getSerialPorts(): List<String> {
        val serialPorts: MutableList<String> = ArrayList()
        val devDir = File("/dev")

        if (devDir.isDirectory) {
            val files = devDir.listFiles()
            if (files != null) {
                for (file in files) {
                    if (isSerialPort(file.name)) {
                        serialPorts.add(file.absolutePath)
                    }
                }
            }
        }
        return serialPorts
    }

    private fun isSerialPort(fileName: String): Boolean {
        return fileName.startsWith("ttyS") || fileName.startsWith("ttyUSB")
    }

    fun saveConfig(ctx: Context, dockList: MutableList<DockTestFragment.DockTestBean>, port: String?) {
        if (port.isNullOrEmpty()) {
            ToastUtils.tip(R.string.please_select_port)
            return
        }
        ToastUtils.tip(R.string.save_success)
        BusinessManager.disconnectDock()
        SPUtils.saveDockConfig(mContext!!, Gson().toJson(dockList))
        SPUtils.savePortConfig(mContext!!, port)
        restartApp(ctx)
    }

    private fun restartApp(ctx: Context) {
        ctx.packageManager?.getLaunchIntentForPackage(ctx.packageName)?.let {
            it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            ctx.startActivity(it)
        }
        exitProcess(0)
    }
}