package main

import (
	"fmt"
	"io"
	"net"
	"time"
)

func runClient() error {
	var conn net.Conn
	var err error

	for i := 0; i < config.MaxRetries; i++ {
		conn, err = net.Dial("tcp", config.ServerAddress)
		if err == nil {
			break
		}
		fmt.Printf("Connection attempt %d failed: %v\n", i+1, err)
		time.Sleep(time.Duration(config.ReconnectInterval) * time.Second)
	}

	if err != nil {
		return fmt.Errorf("failed to connect after %d attempts", config.MaxRetries)
	}
	defer conn.Close()

	fmt.Println("Connected to server")

	for {
		if err := handleConnection(conn); err != nil {
			resetReciverConnectGPIO()
			return err
		}
	}
}

func handleConnection(conn net.Conn) error {
	setReciverConnectGPIO()

	for {
		conn.SetReadDeadline(time.Now().Add(time.Duration(config.ReadTimeout) * time.Second))

		sizeBuf := make([]byte, 1)
		_, err := conn.Read(sizeBuf)
		if err != nil {
			return fmt.Errorf("error reading size: %v", err)
		}

		size := int(sizeBuf[0])

		if size == 0 {
			continue
		}

		fmt.Printf("Received size: %d\n", size)
		buf := make([]byte, size-1)
		_, err = io.ReadFull(conn, buf)
		if err != nil {
			return fmt.Errorf("error reading data: %v", err)
		}

		fmt.Printf("Received data: %v\n", buf)
		fmt.Printf("Received size: %v\n", len(buf))
		fullData := append(sizeBuf, buf...)

		logEntry, err := Deserialize(fullData)
		if err != nil {
			return fmt.Errorf("deserialization error: %v", err)
		}

		formData, err := convertToFormData(logEntry)
		if err != nil {
			return fmt.Errorf("JSON conversion error: %v", err)
		}

		if err := sendToRESTAPIForm(formData); err != nil {
			return fmt.Errorf("REST API error: %v", err)
		}
	}
}
