package main

import (
	"encoding/hex"
	"fmt"
	"net"
	"os"
	"sparrow/pkg/coap"
	"sparrow/pkg/protocol"
	"sparrow/pkg/tlv"
	"time"
)

const url = "127.0.0.1:56883"

func main() {
	addr, err := net.ResolveUDPAddr("udp", url)
	if err != nil {
		fmt.Println("Can't resolve address: ", err)
		os.Exit(1)
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		fmt.Println("Can't dial: ", err)
		os.Exit(1)
	}
	defer conn.Close()
	token, _ := hex.DecodeString("e30680acf77ecd60")
	payloadHead := protocol.DataHead{
		Flag:      0,
		Timestamp: uint64(time.Now().Unix() * 1000),
	}
	param1 := []interface{}{uint32(3), float32(1.2), int64(10)}
	params1, err := tlv.MakeTLVs(param1)
	if err != nil {
		fmt.Println(err)
	}
	sub1 := protocol.SubData{
		Head: protocol.SubDataHead{
			SubDeviceid: uint16(1),
			PropertyNum: uint16(1),
			ParamsCount: uint16(len(params1)),
		},
		Params: params1,
	}
	param2 := []interface{}{uint32(4), int64(11)}
	params2, err := tlv.MakeTLVs(param2)
	if err != nil {
		fmt.Println(err)
	}
	sub2 := protocol.SubData{
		Head: protocol.SubDataHead{
			SubDeviceid: uint16(1),
			PropertyNum: uint16(2),
			ParamsCount: uint16(len(params2)),
		},
		Params: params2,
	}

	payload := &protocol.Data{
		Head:    payloadHead,
		SubData: []protocol.SubData{},
	}
	payload.SubData = append(payload.SubData, sub1)
	payload.SubData = append(payload.SubData, sub2)

	buf, err := payload.Marshal()
	if err != nil {
		if err != nil {
			fmt.Println(err)
		}
	}
	req := &coap.BaseMessage{
		Code:      coap.POST,
		Type:      coap.CON,
		MessageID: 2,
		//Token:     []byte{0, 1, 0x2, 3, 4, 5, 6, 7, 8, 9, 1, 12, 12, 1, 2, 1, 2, 2},
		Token:   token,
		Payload: buf,
	}
	req.SetPathString("/2")
	bytes, err := req.Encode()
	if err != nil {
		fmt.Printf("dial err %s", err.Error())
	}
	conn.Write(bytes)
	msg := make([]byte, 20)

	_, err = conn.Read(msg)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Printf("Response:%#v", msg)

}
