package misc

import (
	"encoding/json"
	"fmt"
	"netease_control_center/interfaces/log"
	"netease_control_center/nembd/controller/adau1761"
	"netease_control_center/nembd/controller/micadc"
	"os"
	"sync/atomic"
	"time"
	"netease_control_center/globals"
)

var (
	lasttrigvol       = -999
	muteflag    int32 = 0
)

type AdcReg struct {
	Addr int `json:"addr"`
	Val  int `json:"val"`
}
type AdcRegs struct {
	BC AdcReg `json:"0xbc"`
	BD AdcReg `json:"0xbd"`
	BE AdcReg `json:"0xbe"`
	BF AdcReg `json:"0xbf"`
}
type AdcChanel struct {
	Adc0 []AdcReg `json:"adc0"`
	Adc1 []AdcReg `json:"adc1"`
}

func (this *AdcChanel) Write2Adc() {
	t := time.Now()
	for _, v := range this.Adc0 {
		//log.Println(log.ErrorLog, "Write adc0:", v.Addr, v.Val)
		micadc.MicAdcSet(0, v.Addr, v.Val)
	}
	for _, v := range this.Adc1 {
		//log.Println(log.ErrorLog, "Write adc1:", v.Addr, v.Val)
		micadc.MicAdcSet(1, v.Addr, v.Val)
	}

	fmt.Println("write ok, coast:", time.Now().Sub(t))
}

var (
	voladcMap = make(map[int]AdcChanel)
)

func InitVoladc() {
	path := "/usr/share/golang/vol_adc.config"
	if fd, err := os.Open(path); err == nil {
		defer fd.Close()

		if err = json.NewDecoder(fd).Decode(&voladcMap); err == nil {
			log.Println(log.DebugLog, "Init voladc success!")
		} else {
			log.Println(log.ErrorLog, "Json err:", err)
		}
	} else {
		log.Println(log.ErrorLog, "Can not open:", path, err)
	}

	IdleMicAdc()
}

//adau静音接口
func adauMute(isMute bool) {
	if isMute {
		if atomic.LoadInt32(&muteflag) == 0 {
			log.Println(log.DebugLog, "++++++++++++++++  Set mute true  +++++++++++++++++")
			atomic.StoreInt32(&muteflag, 1)
			adau1761.Mute(true)
		}
	} else {
		if atomic.LoadInt32(&muteflag) == 1 {
			log.Println(log.DebugLog, "++++++++++++++++  Set mute false  ++++++++++++++++")
			atomic.StoreInt32(&muteflag, 0)
			adau1761.Mute(false)
		}
	}
}

func VolTrigeMicAdc() {
	adauMute(false)
	vol, _ := adau1761.GetVol()
	if globals.GetCurPlatformConfig().MicAdc == true {
		if (lasttrigvol >= -1 && lasttrigvol <= 12 && vol <= 12) || (lasttrigvol == vol) {
			lasttrigvol = vol
			return
		} else {
			lasttrigvol = vol
		}
		if v, ok := voladcMap[vol]; ok {
			log.Println(log.ErrorLog, "Write vol:", vol, v)
			v.Write2Adc()
		} else {
			log.Println(log.ErrorLog, "Can not find vol adc regs:", vol)
		}
	}
}

func IdleMicAdc() {
	adauMute(true)

	if globals.GetCurPlatformConfig().MicAdc == true {
		if lasttrigvol >= -1 && lasttrigvol <= 12 {
			return
		} else {
			lasttrigvol = -1
		}

		adcval := AdcChanel{Adc0: []AdcReg{AdcReg{Addr: 0xbc, Val: 0x38}, AdcReg{Addr: 0xbd, Val: 0x38}, AdcReg{Addr: 0xbe, Val: 0x38}, AdcReg{Addr: 0xbf, Val: 0x38}},
			Adc1: []AdcReg{AdcReg{Addr: 0xbc, Val: 0x38}, AdcReg{Addr: 0xbd, Val: 0x38}, AdcReg{Addr: 0xbe, Val: 0x38}, AdcReg{Addr: 0xbf, Val: 0x38}}}

		adcval.Write2Adc()
	}
}
