package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	loginServer *LoginServer
	runLoops    = true
)

func main() {
	// Initialize logging
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.Println("EQ2Emulator Login Server Starting...")

	// Load configuration
	config, err := LoadConfig("login_config.json")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// Initialize login server
	loginServer, err = NewLoginServer(config)
	if err != nil {
		log.Fatalf("Failed to create login server: %v", err)
	}

	// Setup signal handling
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// Start the server
	go func() {
		if err := loginServer.Start(); err != nil {
			log.Fatalf("Server failed to start: %v", err)
		}
	}()

	// Start maintenance routines
	go startMaintenanceTimers()

	log.Printf("Login server listening on port %d", config.Port)

	// Wait for shutdown signal
	<-sigChan
	log.Println("Shutdown signal received, stopping server...")

	runLoops = false
	loginServer.Stop()
	log.Println("Server stopped.")
}

// startMaintenanceTimers starts periodic maintenance tasks
func startMaintenanceTimers() {
	statsTicker := time.NewTicker(60 * time.Second)
	cleanupTicker := time.NewTicker(5 * time.Minute)

	defer statsTicker.Stop()
	defer cleanupTicker.Stop()

	for runLoops {
		select {
		case <-statsTicker.C:
			loginServer.UpdateStats()
		case <-cleanupTicker.C:
			loginServer.CleanupStaleConnections()
		}
	}
}
