package main

import (
	"bth-rs30-gateway/protocol"
	"bth-rs30-gateway/server"
	"context"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gproc"
	"os"
	"sparrow-sdk/config"
	"sparrow-sdk/protocal"
	gatewayV2 "sparrow-sdk/v2"
)

func main() {
	ctx := context.Background()
	err := glog.SetLevelStr(g.Cfg().GetString("Server.RunMode"))
	if err != nil {
		panic(err)
	}
	gw := gatewayV2.NewGateway(&config.Config{
		SparrowServer: g.Cfg().GetString("Sparrow.Server"),
		ProductKey:    g.Cfg().GetString("Sparrow.ProductKey"),
		Protocol:      "mqtt",
		DeviceCode:    g.Cfg().GetString("Sparrow.DeviceCode"),
		Version:       "1.0.0",
		Debug:         g.Cfg().GetBool("Sparrow.Debug"),
	})
	if _, err = gw.Register(); err != nil {
		panic(err)
	}
	if _, err = gw.Authentication(); err != nil {
		panic(err)
	}
	// 通用指令回调
	gw.SetReportCommandCallback(func(deviceCode, subId string) error {
		return nil
	})
	go gw.Connect()

	srv := server.NewServer(
		ctx,
		g.Cfg().GetString("Server.Addr"),
		g.Cfg().GetInt("Server.Port"),
		gw,
	)
	go func() {
		if err := srv.Start(); err != nil {
			panic(err)
		}
	}()
	closeReportChan := make(chan struct{})
	go func() {
		for {
			select {
			case msg := <-gw.RecvCommand():
				if msg.Data.Cmd == "SetOffset" {

				}
			case <-closeReportChan:
				return
			}
		}
	}()
	if err = gw.RegisterCommand("SetOffset", func(msg protocal.CloudSend) error {
		var params protocol.SetOffSetParams
		j := gjson.New(msg.Data.Params)
		err = j.Struct(&params)
		if err != nil {
			glog.Errorf("错误的指令参数%s", err.Error())
			return err
		}
		glog.Debugf("指令:%s, 子设备Id:%s, 参数:%v", msg.Data.Cmd, msg.SubDeviceId, params)
		client := srv.GetClient(msg.SubDeviceId)
		if client != nil {
			if err = client.SetOffset(params.Act, params.Value, 1); err != nil {
				glog.Errorf("执行命令出错:%s", err.Error())
				return err
			}
		}
		return nil
	}); err != nil {
		panic(err)
	}
	if err = gw.RegisterCommand("GetOffset", func(msg protocal.CloudSend) error {
		glog.Debugf("指令:%s, 子设备Id:%s", msg.Data.Cmd, msg.SubDeviceId)
		client := srv.GetClient(msg.SubDeviceId)
		if client != nil {
			client.GetOffset()
		}
		return nil
	}); err != nil {
		panic(err)
	}

	gproc.AddSigHandlerShutdown(func(sig os.Signal) {
		gw.Close()
		srv.Stop()
	})
	gproc.Listen()
}
