package main

import (
	"blazing/common/rpc"
	"blazing/common/socket"

	"blazing/cool"
	"blazing/logic/controller"
	"blazing/logic/service/player"

	blservice "blazing/modules/blazing/service"

	"fmt"
	"log"
	"math/rand"
	"net"
	"time"

	"github.com/gogf/gf/v2/util/gconv"
)

const (
	minRandomPort     = 10000
	maxRandomPort     = 60000
	maxPortRetryCount = 5
)

var defaultPort = gconv.Int(cool.Config.Port) //读入默认的端口

// determinePort 确定服务器使用的端口
func determinePort(serverid uint16) (int, error) {
	rand.Seed(time.Now().UnixNano())
	if serverid == 0 {
		return defaultPort, nil
	}

	for i := 0; i < maxPortRetryCount; i++ {
		port := generateRandomPort()
		if isPortAvailable(port) {
			return port, nil
		}
		log.Printf("Port %d is not available, retrying...", port)
	}

	return 0, fmt.Errorf("failed to find available port after %d attempts", maxPortRetryCount)
}

// generateRandomPort 生成指定范围内的随机端口
func generateRandomPort() int {
	return minRandomPort + rand.Intn(maxRandomPort-minRandomPort)
}

// isPortAvailable 检查端口是否可用
func isPortAvailable(port int) bool {
	address := fmt.Sprintf(":%d", port)
	listener, err := net.Listen("tcp", address)
	if err != nil {
		return false
	}
	defer listener.Close()
	return true
}

// 如果id是0,那就是login server
func Start(serverid uint16) {
	//ants.NewPool(100)
	head := player.NewTomeeHandler()
	head.Callback = controller.Recv
	if serverid != 0 { //logic服务器
		// 确定端口
		port, err := determinePort(serverid)
		if err != nil {
			log.Fatalf("Failed to determine port: %v", err)
		}

		//	go func() {
		t := rpc.StartClient(serverid, uint16(port), new(controller.LogicClient))

		controller.Maincontroller.RPCClient = *t      //将RPC赋值Start
		controller.Maincontroller.Port = uint16(port) //赋值服务器ID

		blservice.NewLoginServiceService().SetServerID(serverid, gconv.Uint16(port), t)
		socket.
			NewServer(
				socket.WithCORS(),
				socket.WithPort(port),

				socket.WithSocketHandler(head)).
			Boot()

	} else {
		go rpc.StartServer()

		//go rpcserver() //对login tcp启动
		//ants.Submit(rpcserver)
		socket.NewServer(
			socket.WithCORS(),
			socket.WithPort(defaultPort),
			socket.WithSocketHandler(head)).Boot()
	}

}
