package server

import (
	"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)
	nc            *gtcp.Conn
	lastHeartBeat time.Time
	done          chan struct{}
	gatewayId     uint16

}


func (c *Client) ReadLoop() {
	defer c.srv.grWG.Done()
	for {
		buf, err := c.nc.RecvTil([]byte{0x16})
		if err != nil {
			c.readError(err)
			return
		}
		if len(buf) > 0 {
			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.nc.Close()
	c.nc = nil
	close(c.done)
	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.nc == nil {
		return nil
	}
	err := c.nc.Send(buf)
	if err != nil {
		glog.Error(err)
		c.closeConnection()
		return err
	}
	return nil
}

