package server

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/gtcp"
	gatewayV2 "sparrow-sdk/v2"
	"time"
)

type Server struct {
	closeChan chan struct{}
	srv       *gtcp.Server
	ctx       context.Context
	addr      string
	port      int
	gateWay   *gatewayV2.Gateway
	clients   *gmap.Map
}

func NewServer(ctx context.Context, addr string, port int, gw *gatewayV2.Gateway) *Server {
	return &Server{
		closeChan: make(chan struct{}),
		ctx:       ctx,
		addr:      addr,
		port:      port,
		gateWay:   gw,
		clients:   gmap.New(false),
	}
}

func (s *Server) Start() error {
	g.Log().Printf(s.ctx, "服务端启动[%s:%d]", s.addr, s.port)
	srv := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect)
	s.srv = srv
	return s.srv.Run()
}

func (s *Server) Stop() {
	s.clients.Iterator(func(k interface{}, v interface{}) bool {
		client := v.(*Client)
		close(client.closeChan)
		return true
	})
	_ = s.srv.Close()
}

func (s *Server) onClientConnect(conn *gtcp.Conn) {
	g.Log().Debugf(s.ctx, "新的设备接入:%s", conn.RemoteAddr())
	client := NewClient(s, conn)
	client.closeHandler = func(id string, c *Client) {
		g.Log().Debugf(s.ctx, "客户端断开:%s", id)
		if id != "" {
			_ = s.gateWay.SubDeviceLogout(GetConfig("sparrow.DeviceCode").String(), id)
			s.clients.Remove(id)
		}
	}
	client.regHandler = func(id string, c *Client) {
		_ = s.gateWay.SubDeviceLogin(GetConfig("Sparrow.DeviceCode").String(), id)
		s.clients.Set(id, c)
	}

	go client.SendLoop()

	time.Sleep(10 * time.Second)

	go client.GetStatus()

	//go client.GetSensorStatus()

	//go client.Read()
}

func (s *Server) ReportStatus(subId string, data interface{}, cmd string) error {
	return s.gateWay.ReportStatus(subId, cmd, data)
}

func (s *Server) GetClient(subId string) *Client {
	client := s.clients.Get(subId)
	if client != nil {
		return client.(*Client)
	}
	return nil
}

func GetConfig(key string) *gvar.Var {
	ret, err := g.Cfg().Get(context.Background(), key)
	if err != nil {

	}
	return ret
}
