package main

import (
	"fmt"
	"log"
	"os"

	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/uds"
)

type Request struct {
	Name    string `json:"name"`
	Message string `json:"message"`
}

type Response struct {
	Status string `json:"status"`
}

const socketPath = "/usr/local/bin/jobarranger/icon_result_manager.sock"

func udsServerExample(ready chan struct{}) {
	var req common.EventData
	os.Remove(socketPath)
	listener, err := uds.CreateUdsServer(socketPath)
	if err != nil {
		fmt.Println("server listen error:", err.Error())
		os.Exit(1)
	}
	defer func() {
		if err := listener.Close(); err != nil {
			log.Printf("Error closing listener: %v", err)
		}
	}()

	close(ready)

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("server accept error:", err.Error())
			os.Exit(1)
		}

		if _, err := conn.Receive(); err != nil {
			fmt.Println("receive error:", err.Error())
			os.Exit(1)
		}
		fmt.Println("Request:", req)

		// resp := Response{Status: "OK"}
		// if err := conn.Send(resp); err != nil {
		// 	fmt.Println("send error:", err.Error())
		// 	os.Exit(1)
		// }
	}
}

func udsClientExample() {
	client := uds.CreateUdsClient(socketPath, 1)

	conn, err := client.Connect()
	if err != nil {
		fmt.Println("client connect error:", err.Error())
		os.Exit(1)
	}
	defer conn.Close()

	request := Request{
		Name:    "UnixSocketClient",
		Message: "Hello via UDS",
	}
	if err := conn.Send(&request); err != nil {
		fmt.Println("client send error:", err.Error())
		os.Exit(1)
	}

	var resp Response
	if _, err := conn.Receive(); err != nil {
		fmt.Println("client receive error:", err.Error())
		os.Exit(1)
	}
	fmt.Println("Response:", resp)
}

func main() {
	fmt.Println("UDS Server listening...")

	// wait for server to start
	ready := make(chan struct{})

	go func() {
		udsServerExample(ready)
	}()

	<-ready
	select {}
	// udsClientExample()
	fmt.Println("Done sending via UDS")
}
