package middleware

import (
	"bufio"
	"context"
	"encoding/binary"
	"io"
	"log"
	"net"
	"time"

	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/lxzan/gws"
)

const PingInterval = 10 * time.Second

type Handler struct {
	gws.BuiltinEventHandler
	port   int
	target net.Conn
}

func (c *Handler) OnOpen(socket *gws.Conn) {
	target, err := net.Dial("tcp", "127.0.0.1:"+gconv.String(c.port))

	if err != nil {
		glog.Debug(context.Background(), "连接失败")
	}
	c.target = target
	//errChan := make(chan error, 2)
	if c.target == nil {
		return
	}
	go func(conn net.Conn, socket *gws.Conn) {
		reader := bufio.NewReader(conn)
	LOOP:
		for {

			//	select {
			//	default:
			packlen, err := reader.Peek(4)

			if err != nil {
				socket.WriteClose(1000, nil)
				break LOOP
			}

			length := int32(binary.BigEndian.Uint32(packlen))

			data := make([]byte, length)
			io.ReadFull(reader, data)

			//pack_Ver := data[4] //因为包体已经解析，所以这里直接取0
			//	var pack = make([]byte, length)

			socket.WriteMessage(gws.OpcodeBinary, data)
			//t.event.RecvHandler(pack)
			//	client.OnReceiveBase(client, pack, length)

		}
	}(c.target, socket)
	//err = <-errChan
	if err != io.EOF {
		log.Println("proxy error:", err)

	}
}

func (c *Handler) OnPing(socket *gws.Conn, payload []byte) {
	_ = socket.SetDeadline(time.Now().Add(2 * PingInterval))
	_ = socket.WritePong(nil)
}

func (c *Handler) OnPong(socket *gws.Conn, payload []byte) {}

func (c *Handler) OnMessage(socket *gws.Conn, gwsmessage *gws.Message) {
	if c.target != nil {
		c.target.Write(gwsmessage.Bytes())
	}
	//fmt.Println(gwsmessage.Bytes())

}

func (c *Handler) OnClose(socket *gws.Conn, err error) {

	glog.Debug(context.Background(), "断开连接")
	if c.target != nil {
		c.target.Close()

	}

}

// RemoveSocket 移除WebSocket连接

func messeunpack(id int64, x []byte) {

	// json := gjson.ParseBytes(x)
	// json.ForEach(func(key, value gjson.Result) bool {
	// 	fmt.Println(key, value)
	// 	numeric := regexp.MustCompile(`\d`).MatchString(value.String())

	// 	var ob int
	// 	if numeric { //如果正确  则使用常量

	// 	} else { //如果错误，则使用变量，即从数据库查询常量定义值是多少

	// 	}

	// 	work.User_script(uint(id), strings.Trim(message.Data.String(), " "))
	// 	// switch s:=value.String() {
	// 	// case regexp.MustCompile(`\d`).MatchString(s):

	// 	// }

	// 	return true
	// })
	// json.Get("1").String()
	// var ob int
	// numeric := regexp.MustCompile(`\d`).MatchString(json.Get("1").String())
	// if numeric { //如果正确  则使用常量
	// 	ob, _ = strconv.Atoi(json.Get("1").String())
	// } else { //如果错误，则使用变量，即从数据库查询常量定义值是多少
	// 	ob, _ = strconv.Atoi(json.Get("1").String())
	// }
	// switch ob {
	// case 1: //发包函数
	// 	work.User_script(uint(id), strings.Trim(message.Data.String(), " "))
	// }

	// Go 1.9.7 onwards only.

}
