package earlyWarning

import (
	"PPOSUtils/utils"
	"fmt"
	"net"
	"net/url"
	"strings"
)

func NewUdpClient(ip, port, version string) *UdpClient {
	return &UdpClient{
		ip:      ip,
		port:    port,
		version: version,
	}
}

type UdpClient struct {
	ip      string
	port    string
	version string
}

type Request struct {
	Client    *UdpClient
	params    url.Values
	udpConn   *net.UDPConn
	dataSlice [][]byte
}

func (that *Request) conn() (*net.UDPConn, error) {
	if that.udpConn == nil {
		_addr := &net.UDPAddr{
			IP:   net.ParseIP(that.Client.ip),
			Port: utils.ToInt(that.Client.port),
		}
		_socket, _err := net.DialUDP("udp", nil, _addr)
		//fmt.Println(that.Client.ip, "======", _socket, _err, utils.ToInt(that.Client.port))
		if _err != nil {
			fmt.Println("连接服务端失败，err:", _err)
			return nil, _err
		}
		that.udpConn = _socket
	}
	return that.udpConn, nil
}

//返回的“信息头”---包含将要返回多少字节给客户端
func (this *Request) fiexLeninfo(str string, l int) []byte {
	minsend := make([]byte, l)
	first := append([]byte(str), minsend...)
	first = first[0:l]
	return first
}

//过滤空字节
func (this *Request) trim(b []byte) string {
	emptyByte := make([]byte, 1)
	return strings.TrimSpace(strings.Trim(string(b), string(emptyByte)))
}

func (that *Request) Push(address string, params ...interface{}) *Request {
	_sendData := []byte{}
	if len(params) > 0 {
		_data := params[0]
		switch d := _data.(type) {
		case []byte:
			_sendData = d
		case string:
			_sendData = []byte(d)
		}
	}
	_path := []string{
		"api",
		that.Client.version,
	}
	if address != "" {
		_path = append(_path, address)
	}
	_sendData = append(that.fiexLeninfo(strings.Join(_path, "."), 60), _sendData...)
	that.dataSlice = append(that.dataSlice, _sendData)
	return that
}

func (that *Request) Save() error {
	_conn, _err := that.conn()
	if _err != nil {
		fmt.Println("====== save error 001 =====", _err.Error())
		return _err
	}
	defer that.Close()
	for _, _data := range that.dataSlice {
		if _, _err := _conn.Write(_data); _err != nil {
			fmt.Println("====== save error 002 =====", _err.Error())
			return _err
		}
		fmt.Println("====== save =====", string(_data))
	}
	return nil
}

func (that *Request) Close() {
	if that.udpConn != nil {
		that.udpConn.Close()
		that.udpConn = nil
	}
}
