package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"time"

	toki "git.toki-labs.com/toki/proto-socket/go"
	"git.toki-labs.com/toki/proto-socket/go/packets"

	"google.golang.org/protobuf/proto"
)

func parserMap() toki.ParserMap {
	return toki.ParserMap{
		toki.TypeNameOf(&packets.TestData{}): func(b []byte) (proto.Message, error) {
			m := &packets.TestData{}
			return m, proto.Unmarshal(b, m)
		},
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	server := toki.NewTcpServer("127.0.0.1", 19090, func(conn net.Conn) *toki.TcpClient {
		return toki.NewTcpClient(conn, 30, 10, parserMap())
	})
	server.OnClientConnected = func(client *toki.TcpClient) {
		toki.AddRequestListenerTyped[*packets.TestData, *packets.TestData](&client.Communicator, func(req *packets.TestData) (*packets.TestData, error) {
			return &packets.TestData{
				Index:   req.GetIndex(),
				Message: "echo: " + req.GetMessage(),
			}, nil
		})
	}
	if err := server.Start(ctx); err != nil {
		log.Fatal(err)
	}
	defer server.Stop()

	client, err := toki.DialTcp(ctx, "127.0.0.1", 19090, 30, 10, parserMap())
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	res, err := toki.SendRequestTyped[*packets.TestData, *packets.TestData](
		&client.Communicator,
		&packets.TestData{Index: 1, Message: "hello tcp"},
		2*time.Second,
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.GetMessage())
}
