package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

func PlayMultiplayer(addr string) {
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		fmt.Printf("Error connecting to %s: %v\n", addr, err)
		os.Exit(1)
	}
	defer conn.Close()
	fmt.Printf("Connected to %s\n", addr)
	fmt.Fprintln(conn, "HELLO")
	serverReader := bufio.NewReader(conn)
	clientReader := bufio.NewReader(os.Stdin)
	welcome, _ := serverReader.ReadString('\n')
	fmt.Print(welcome)
	line, _ := serverReader.ReadString('\n')
	line = strings.TrimSpace(line)
	if line == "WAITING" {
		fmt.Println("Waiting for an opponent...")
		line, _ = serverReader.ReadString('\n')
		line = strings.TrimSpace(line)
	}
	if !strings.HasPrefix(line, "MATCHED") {
		fmt.Println("Failed to join a game.")
		return
	}
	parts := strings.Split(line, " ")
	myColor := parts[2]
	fmt.Printf("\nMatched! You play %s.\n", myColor)
	fmt.Println("Moves: e2e4, g1f3, e7e8q | RESIGN | QUIT")
	fmt.Println()
	gameOver := false
	for !gameOver {
		header, err := serverReader.ReadString('\n')
		if err != nil {
			fmt.Println("\nConnection lost.")
			break
		}
		header = strings.TrimSpace(header)
		switch {
		case header == "BOARD":
			var lines []string
			for {
				bl, err := serverReader.ReadString('\n')
				if err != nil {
					break
				}
				bl = strings.TrimRight(bl, "\n")
				if bl == "" {
					break
				}
				lines = append(lines, bl)
			}
			joined := strings.Join(lines, " ")
			fmt.Println(strings.Join(lines, "\n"))
			fmt.Println()
			if strings.Contains(joined, "WINS") || strings.Contains(joined, "STALEMATE") {
				gameOver = true
			}
		case strings.HasPrefix(header, "ERROR"):
			fmt.Printf("  %s\n", header)
		default:
		}
		if !gameOver {
			fmt.Print("You> ")
			input, _ := clientReader.ReadString('\n')
			input = strings.TrimSpace(input)
			if input == "QUIT" {
				fmt.Println("Disconnecting...")
				break
			}
			fmt.Fprintln(conn, input)
		}
	}
	fmt.Println("Goodbye!")
}

