package controller

import (
	"context"
	"github.com/grandcat/zeroconf"
	"netease_control_center/globals"
	"netease_control_center/interfaces/log"
	"sync"
	"time"
)

const (
	zeroconf_name    = "NE_AUDIO"
	zeroconf_service = "_neaudio._tcp"
	zeroconf_domain  = "local."
	zeroconf_port    = 1705
)

type zeroconf_key string

const (
	zeroconf_key_devname zeroconf_key = "devname"
	zeroconf_key_serial  zeroconf_key = "serial"
)

var (
	zeroconf_text = make(map[zeroconf_key]*string)

	zeroconf_server *zeroconf.Server

	zeroconf_lock sync.Mutex
)

func init() {
	zeroconf_text[zeroconf_key_serial] = &globals.CPU_ID
	zeroconf_text[zeroconf_key_devname] = &globals.BTNAME
}

func GetZeroconfText() []string {
	var tmp []string
	for k, v := range zeroconf_text {
		tmp = append(tmp, string(k)+":"+*v)
	}

	return tmp
}

func StartZeroconf() {
	zeroconf_lock.Lock()
	defer zeroconf_lock.Unlock()

	if zeroconf_server == nil {
		_StartZeroconf()
	}
}

func RestartZeroconf() {
	zeroconf_lock.Lock()
	defer zeroconf_lock.Unlock()

	if zeroconf_server != nil {
		//todo
		return
		zeroconf_server.Shutdown()
	}

	_StartZeroconf()
}

func _StartZeroconf() {
	var err error
	//todo
	return
	zeroconf_server, err = zeroconf.Register(zeroconf_name+"@"+globals.BTNAME, zeroconf_service, zeroconf_domain, zeroconf_port, GetZeroconfText(), nil)
	if err != nil {
		log.Println(log.DebugLog, "zeroconf start err:", err)
	} else {
		log.Println(log.DebugLog, "Zeroconf start success!")
	}
}

func SetZeroconfText(key zeroconf_key, val string) {
	zeroconf_lock.Lock()
	defer zeroconf_lock.Unlock()

	zeroconf_text[key] = &val

	if zeroconf_server == nil {
		_StartZeroconf()
	} else {
		zeroconf_server.SetText(GetZeroconfText())
	}
}

func DiscoveryFriendDev() {
	if resolver, err := zeroconf.NewResolver(nil); err == nil {
		entries := make(chan *zeroconf.ServiceEntry)
		go func(results <-chan *zeroconf.ServiceEntry) {
			for entry := range results {
				log.Println(log.DebugLog, *entry)
			}
		}(entries)

		ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
		defer cancel()
		err = resolver.Browse(ctx, "_neaudio._tcp", "local.", entries)
	} else {
		log.Println(log.ErrorLog, "Start zeroconf client error! ", err)
	}

}
