package server

import (
	"context"
	"dlt645-server/protocol"
	"fmt"
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/gtcp"
	"github.com/gogf/gf/os/glog"
	gatewayV2 "sparrow-sdk/v2"
	"sync"
	"time"
)

type Server struct {
	closeChan chan struct{}
	server    *gtcp.Server
	ctx       context.Context
	addr      string
	port      int
	grMu      sync.Mutex
	grWG      sync.WaitGroup
	message   protocol.Message
	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 {
	glog.Printf("服务端启动[%s:%d]", s.addr, s.port)
	server := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect)
	s.server = server
	return s.server.Run()
}

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

func (s *Server) onClientConnect(conn *gtcp.Conn) {
	glog.Debugf("新的设备接入:%s", conn.RemoteAddr())
	c := NewClient(s, conn)
	c.closeHandler = func(id string, c *Client) {
		glog.Debugf("客户端断开:%s", id)
		if id != "" {
			_ = s.gateWay.SubDeviceLogout(g.Cfg().GetString("Sparrow.DeviceCode"), id)
			s.clients.Remove(id)
		}
	}
	c.regHandler = func(id string, c *Client) {
		_ = s.gateWay.SubDeviceLogin(g.Cfg().GetString("Sparrow.DeviceCode"), id)
		s.clients.Set(id, c)
	}
	err := c.SendGetAddress()
	if err != nil {
		return
	}

	time.Sleep(10 * time.Second)

	go c.SendLoop()

	go c.GetActivePower()

	go c.GetVBlock()

	go c.GetIBlock()

}

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