package rpc

import (
	"blazing/common/data/share"
	"blazing/cool"
	"context"
	"fmt"
	"log"
	"net/http"

	"github.com/filecoin-project/go-jsonrpc"
)

const rpcaddr = "127.0.0.1:40000"

var clientmap = make(map[uint16]*ClientHandler) //客户端map
var clientidmap = make(map[uint16]uint16)       //客户端map
//var usermap = make(map[int]int)              //用户->客户端的map

// Define the client handler interface
type ClientHandler struct {
	KickPerson func(uint32) error //踢人,这里是返回具体的logic
	QuitSelf   func(int) error    //关闭服务器进程
}

// Define the server handler
type ServerHandler struct{}

// 实现踢人
func (h *ServerHandler) Kick(ctx context.Context, userid uint32) error {

	useid1, err := share.ShareManager.GetUserOnline(userid)

	if err != nil {
		return fmt.Errorf("user not found")
	}

	return clientmap[useid1].KickPerson(userid) //实现指定服务器踢人
	// for _, v := range clientmap {
	// 	err := v.KickPerson(userid)
	// 	if err != nil {
	// 		return fmt.Errorf("call on client: %w", err)
	// 	}
	// }

	//return nil
}

// 注册logic服务器
func (h *ServerHandler) RegisterLogic(ctx context.Context, id, port uint16) error {
	//TODO 待修复滚动更新可能导致的玩家可以同时在旧服务器和新服务器同时在线的bug
	revClient, ok := jsonrpc.ExtractReverseClient[ClientHandler](ctx)
	if !ok {
		return fmt.Errorf("no reverse client")
	}

	aa, ok := clientidmap[id]
	if ok { //如果已经存在且这个端口已经被存过

		t := clientmap[aa]
		t.QuitSelf(0)
	}
	clientmap[port] = &revClient
	clientidmap[id] = port
	return nil

}

func StartServer() {
	// create a new server instance
	rpcServer := jsonrpc.NewServer(jsonrpc.WithReverseClient[ClientHandler](""))

	rpcServer.Register("", &ServerHandler{})
	cool.Loger.Debug(context.Background(), "jsonrpc server start")
	// go time.AfterFunc(3000, func() {
	// 	testjsonrpc()
	// })

	err := http.ListenAndServe(rpcaddr, rpcServer)
	cool.Loger.Debug(context.Background(), "jsonrpc server fail", err)
}

var closer jsonrpc.ClientCloser

func StartClient(id, port uint16, callback any) *struct {
	Kick func(uint32) error

	RegisterLogic func(uint16, uint16) error
} {

	closer1, err := jsonrpc.NewMergeClient(context.Background(),
		"ws://"+rpcaddr, "", []interface{}{
			&RPCClient,
		}, nil, jsonrpc.WithClientHandler("", callback),
		jsonrpc.WithReconnFun(func() { RPCClient.RegisterLogic(id, port) }),//TODO ，这里会出现server0注册？
	)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	//if port != 0 { //注册logic
		RPCClient.RegisterLogic(id, port)

	//}

	closer = closer1
	return &RPCClient
}

// 关闭客户端
func CloseClient() {
	if closer != nil {
		closer()
	}
}

// Setup RPCClient with reverse call handler
var RPCClient struct {
	Kick func(uint32) error //踢人

	RegisterLogic func(uint16, uint16) error

	//	UserLogin  func(int32, int32) error //用户登录事件
	//	UserLogout func(int32, int32) error //用户登出事件
}
