package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"syscall"

	"go-ts/pkg/ts3client"
)

func main() {
	serverAddr := flag.String("server", "127.0.0.1:9987", "TeamSpeak 3 Server Address")
	nickname := flag.String("nickname", "GoBot", "Nickname")
	flag.Parse()

	log.Printf("=== TeamSpeak Library Example ===")
	log.Printf("Server: %s", *serverAddr)
	log.Printf("Nickname: %s", *nickname)

	// Create client
	client := ts3client.New(*serverAddr, ts3client.Config{
		Nickname: *nickname,
	})

	// Register event handlers
	client.On(ts3client.EventConnected, func(e *ts3client.ConnectedEvent) {
		log.Printf("✓ Connected! ClientID=%d, Server=%s", e.ClientID, e.ServerName)
	})

	client.On(ts3client.EventChannelList, func(e *ts3client.ChannelListEvent) {
		log.Printf("✓ Received %d channels:", len(e.Channels))
		for _, ch := range e.Channels {
			log.Printf("   [%d] %s", ch.ID, ch.Name)
		}

		// Join first non-default channel
		for _, ch := range e.Channels {
			if ch.ID != 1 && ch.ParentID == 0 {
				log.Printf("Joining channel: %s (ID=%d)", ch.Name, ch.ID)
				client.JoinChannel(ch.ID)
				break
			}
		}
	})

	client.On(ts3client.EventMessage, func(e *ts3client.MessageEvent) {
		log.Printf("[%s] %s: %s", e.TargetMode.String(), e.SenderName, e.Message)

		// Echo back channel messages
		if e.TargetMode == ts3client.MessageTargetChannel {
			client.SendChannelMessage("Echo: " + e.Message)
		}
	})

	client.On(ts3client.EventClientEnter, func(e *ts3client.ClientEnterEvent) {
		log.Printf("→ Client joined: %s (ID=%d)", e.Nickname, e.ClientID)
	})

	client.On(ts3client.EventClientLeft, func(e *ts3client.ClientLeftEvent) {
		log.Printf("← Client left: ID=%d (%s)", e.ClientID, e.Reason)
	})

	client.On(ts3client.EventAudio, func(e *ts3client.AudioEvent) {
		// Example: Echo audio (reduce volume)
		for i := range e.PCM {
			e.PCM[i] = e.PCM[i] / 4
		}
		client.SendAudio(e.PCM)
	})

	client.On(ts3client.EventError, func(e *ts3client.ErrorEvent) {
		if e.ID != "0" { // ID 0 = OK
			log.Printf("! Server Error: [%s] %s", e.ID, e.Message)
		}
	})

	// Handle shutdown
	go func() {
		sigChan := make(chan os.Signal, 1)
		signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
		<-sigChan
		log.Println("Shutting down...")
		client.Disconnect()
		os.Exit(0)
	}()

	// Connect (blocks until error or disconnect)
	if err := client.Connect(); err != nil {
		log.Fatalf("Connection error: %v", err)
	}
}
