package online

import (
	mhayaFacade "github.com/mhaya/facade"
	clog "github.com/mhaya/logger"
	"sync"
)

var (
	currentServerId int32 = 0 // 当前游戏节点的serverId
)

var (
	lock        = &sync.RWMutex{}
	playerIdMap = make(map[string]string) // key:playerId, value:agentActorPath
	uidMap      = make(map[int64]string)  // key:UID, value:playerId
)

func BindPlayer(playerId string, uid int64, agentActorPath string) {
	if playerId == "" || uid < 0 || agentActorPath == "" {
		return
	}

	lock.Lock()
	defer lock.Unlock()

	playerIdMap[playerId] = agentActorPath
	uidMap[uid] = playerId
}

func UnBindPlayer(uid mhayaFacade.UID) string {
	if uid < 0 {
		return ""
	}

	lock.Lock()
	defer lock.Unlock()

	playerId, found := uidMap[uid]
	if !found {
		return ""
	}

	delete(playerIdMap, playerId)
	delete(uidMap, uid)

	playerIdCount := len(playerIdMap)
	uidCount := len(uidMap)

	if playerIdCount == 0 || uidCount == 0 {
		clog.Infof("Unbind player uid = %v, playerIdCount = %v, uidCount = %v", uid, playerIdCount, uidCount)
	}

	return playerId
}

func GetPlayerId(uid mhayaFacade.UID) string {
	if uid < 0 {
		return ""
	}

	lock.RLock()
	defer lock.RUnlock()

	if playerId, found := uidMap[uid]; found {
		return playerId
	}

	return ""
}

func Count() int {
	lock.Lock()
	defer lock.Unlock()

	count := len(playerIdMap)
	return count
}
