package tcp_learn

import (
	"fmt"
	"log"
	"net"
	"time"
)

func handleConnection(conn net.Conn) {
	defer conn.Close()

	buf := make([]byte, 1024)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("Error reading:", err)
			break
		}
		if n > 0 {
			fmt.Printf("Received data from %s: %s\n", conn.RemoteAddr(), string(buf[:n]))
		}
	}
}

func TcpServer() {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:8080")
	if err != nil {

		log.Printf("Error accepting connection: %v", err)
	}
	listener, err := net.ListenTCP("tcp", addr)
	if err != nil {
		log.Fatalf("Error creating listener: %v", err)
	}
	defer listener.Close()
	listener.SetDeadline(time.Now().Add(2 * time.Minute))

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("Error accepting connection: %v", err)
			return
		}
		go handleConnection(conn)
	}

}

func TcpClient() chan bool {

	exit := make(chan bool, 1)
	tick := time.Tick(time.Second)
	timeOut := time.After(time.Minute)

	conn, err := net.Dial("tcp", "localhost:8080")

	if err != nil {
		log.Fatalf("Error creating listener: %v", err)
		return nil
	}

	for {
		select {
		case <-timeOut:
			fmt.Println("timeout exit!")
			exit <- true
			return exit
		case <-tick:

			_, err := conn.Write([]byte("Hello from tcp client !"))
			if err != nil {
				log.Fatalf("Error write tcp : %v", err)
			}
		}
	}

	return exit
}
