package atservice

import (
	"netease_control_center/interfaces/log"
	"netease_control_center/nembd"
	_ "netease_control_center/nembd/host/ihw1"
	"time"
)

//忽略AT gpio中断标志，因为dvt将默认的gpio的电平改为高，需要丢弃重启的at gpio 中断
var ignoreAtGpioInt bool = false

func setModeByGpio(value int) {
	if value == 1 {
		log.Println(log.DebugLog, "==================================== at mode")
		McuBootMode = false
		atModeSet(true)
	} else {
		ignoreAtGpioInt = false
		log.Println(log.DebugLog, "==================================== boot mode")
		atModeSet(false)
	}
}

func GetAtGpioState() bool {
	_, err := nembd.NewDigitalPin("GPIO_AT_STATE")
	if err != nil {
		log.Println(log.ErrorLog, "err:", err)
		return false
	}
	nembd.SetDirection("GPIO_AT_STATE", nembd.In)

	v, e := nembd.DigitalRead("GPIO_AT_STATE")

	if e == nil {
		if v == 1 {
			return true
		} else {
			return false
		}
	} else {
		log.Println(log.ErrorLog, "GPIO_AT_STATE=", v, "err=", e)
		return false
	}
}

func AtStateGpioInit() {
	/*h, _, err := nembd.DetectHost()
	if err != nil {
		return
	}

	log.Println(log.DebugLog, h)*/

	atCmdStatePin, err := nembd.NewDigitalPin("GPIO_AT_STATE")
	if err != nil {
		log.Println(log.ErrorLog, "err:", err)
		return
	}
	nembd.SetDirection("GPIO_AT_STATE", nembd.In)

	log.Println(log.WarningLog, "will set at cmd gpio interrupt....")
	atCmdStatePin.Watch(nembd.EdgeBoth, func(stateGpio nembd.DigitalPin) {
		v, _ := stateGpio.Read()
		//log.Println(log.WarningLog, "Gpio state = ", v, ", ignoreAtGpioInt = ", ignoreAtGpioInt)
		if v == 1 && ignoreAtGpioInt == true {
			ignoreAtGpioInt = false
			log.Println(log.WarningLog, "Err Gpio interrupt, disscard -----------------not AT, mcu is boot up------------")
		} else {
			setModeByGpio(v)
		}
	})

	v, e := nembd.DigitalRead("GPIO_AT_STATE")

	if e == nil {
		if v == 1 && ignoreAtGpioInt == true {
			ignoreAtGpioInt = false
			log.Println(log.WarningLog, "Err Gpio state, disscard -----------------not AT, mcu is boot up------------")
		} else {
			setModeByGpio(v)
		}
	} else {
		log.Println(log.ErrorLog, "GPIO_AT_STATE=", v, "err=", e)
		return
	}

	log.Println(log.DebugLog, "AtStateGpioInit done")
}

func ResetMCU() {
	defer func() {
		if r := recover(); r != nil {
			log.Printf(log.WarningLog, "Runtime error caught: %v\n", r)
		}
	}()

	err := nembd.SetDirection("GPIO_RESET", nembd.Out)

	if err == nil {
		atCmdMode = false
		removeAllNode(AT_CMD_FWD_ERR)
		log.Println(log.WarningLog, "will reset mcu ...")
		ignoreAtGpioInt = true /*reset mode , ignore at gpio int*/
		nembd.DigitalWrite("GPIO_RESET", nembd.Low)
		flushUart() //flush uart data
		time.Sleep(20 * time.Millisecond)
		nembd.DigitalWrite("GPIO_RESET", nembd.High)
		nembd.SetDirection("GPIO_RESET", nembd.In)
		//log.Println(log.DebugLog, "reset mcu over")
	} else {
		log.Println(log.ErrorLog, "resetMCUGpioinit err:", err)
	}
}
