package server

import (
	"dlt645-server/protocol"
	"github.com/gogf/gf/encoding/gbinary"
	"github.com/gogf/gf/net/gtcp"
	"github.com/gogf/gf/os/glog"
	"io"
	"net"
	"strings"
	"syscall"
	"time"
)

type Client struct {
	Id            string
	srv           *Server
	conn          *gtcp.Conn
	sendChan      chan []byte
	closeChan     chan struct{}
	closeHandler  func(id string, c *Client)
	lastHeartBeat time.Time
	done          chan struct{}
	gatewayId     uint16
	isReg         bool
}

func (c *Client) ReadLoop() {
	//defer c.srv.grWG.Done()
	for {
		buf, err := c.conn.Recv(-1)
		if err != nil {
			c.readError(err)
			return
		}
		if len(buf) > 0 {
			if !c.isReg {
				id := gbinary.DecodeToString(buf)
				glog.Debugf("收到注册包!id:%s", id)
				c.SetId(id)
				c.isReg = true
				continue
			}
			err = c.srv.message.Decode(buf)
			if err != nil {
				glog.Errorf("解析报文失败:%s", err.Error())
			}
		}
	}
}

func (c *Client) SetId(id string) {
	c.Id = id
}

func (c *Client) readError(err error) {
	defer c.closeConnection()
	if err == io.EOF || isErrConnReset(err) {
		return
	}
	glog.Errorf("读取数据发生错误：%s", err.Error())
}

func (c *Client) closeConnection() {
	_ = c.conn.Close()
	c.conn = nil
	close(c.done)
	c.SetId("")
	c.isReg = false
	if c.closeHandler != nil {
		c.closeHandler(c.Id, c)
	}
}

// isErrConnReset read: connection reset by peer
func isErrConnReset(err error) bool {
	if ne, ok := err.(*net.OpError); ok {
		return strings.Contains(ne.Err.Error(), syscall.ECONNRESET.Error())
	}
	return false
}

func (c *Client) send(buf []byte) error {
	if c.conn == nil {
		return nil
	}
	err := c.conn.Send(buf)
	if err != nil {
		glog.Error(err)
		c.closeConnection()
		return err
	}
	glog.Debugf("指令发送成功:%2X", buf)
	return nil
}

func (c *Client) Send0X3433() {
	//defer c.srv.grWG.Done()
	entity := protocol.Dlt_0x33333433{}
	entity.DeviceAddress = []byte{0x27, 0x12, 0x03, 0x14, 0x07, 0x22}
	for {
		sendByte, _ := entity.Encode()
		err := c.send(sendByte)
		if err != nil {
			glog.Debugf("指令发送失败:%s", err.Error())
		}
		time.Sleep(10 * time.Second)
	}

}

func (c *Client) SendAddress() {
	defer c.srv.grWG.Done()
	for {
		bytea := []byte{0x68, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x68, 0x13, 0x00, 0xDF, 0x16}
		c.send(bytea)
		time.Sleep(5 * time.Second)
	}
}
