package modbus

import (
	"bytes"
	"context"
	"sync/atomic"
	"testing"

	"git.simanc.com/software/golib/v4/gnet"
	"git.simanc.com/software/golib/v4/log"
)

func TestDialer_ReadData(t *testing.T) {
	address := "127.0.0.1:502"
	conn, err := gnet.DialTCP(address)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		_ = conn.Close()
	}()
	mbs := New(conn, log.Console())
	data, err := mbs.ReadData(context.Background(), Code3, 0, 24)
	if err != nil {
		t.Fatal(err)
	}
	t.Log(gnet.Bytes(data).HexTo())
	r := NewSocketReader(bytes.NewReader(data))
	t.Log("curFloor:", r.ReadSingleNumber(2))
	t.Log("check:", r.ReadSingleNumber(3))
	t.Log("taskId:", r.ReadSingleNumber(15))
	t.Log("liftErrClear:", r.ReadSingleNumber(19))
	t.Log("sc1Opened:", r.ReadSingleBool(23, 0))
	t.Log("sc2Opened:", r.ReadSingleBool(23, 1))
}

func TestDialer_WriteData(t *testing.T) {
	address := "127.0.0.1:502"
	conn, err := gnet.DialTCP(address)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		_ = conn.Close()
	}()
	mbs := New(conn, log.Console())

	buf := make([]byte, 4)
	gnet.BigEndian.PutUint32(buf, 999)
	err = mbs.WriteData(context.Background(), Code6, 13, 2, buf)
	if err != nil {
		t.Fatal(err)
	}

	sc1 := new(uint16)
	gnet.SetBit(sc1, 1)

	sc1Buf := make([]byte, 2)
	gnet.BigEndian.PutUint16(sc1Buf, *sc1)

	err = mbs.WriteData(context.Background(), Code6, 23, 1, sc1Buf)
	if err != nil {
		t.Fatal(err)
	}
}

func BenchmarkReadHelper_GetInt64(b *testing.B) {
	exp := gnet.String("00 00 00 00 00 1d 00 03 1a 00 00 03 09 00 01 00 02 00 00 00 00 00 00 00 00 1d 13 00 00 00 00 00 00 00").Hex()
	ato := atomic.Value{}
	ato.Store([]byte(exp))

	for i := 0; i < b.N; i++ {
		buf := ato.Load().([]byte)
		v := ReadHelper(buf)
		_ = v.GetUint64(15)
	}
}
