package logic

import (
	service "Server-Core/Server/Base/Service"
	"Server-Core/Server/GameServer/Server/DB"
	message "Server-Core/Server/Message"
	"time"
)

type PlayerMgr struct {
	playerByClientId map[int]*Player
	playerByPlayerId map[int64]*Player
	playerByUid      map[string]*Player
}

func CreatePlayerMgr() *PlayerMgr {
	mgr := new(PlayerMgr)
	mgr.playerByClientId = make(map[int]*Player)
	mgr.playerByPlayerId = make(map[int64]*Player)
	mgr.playerByUid = make(map[string]*Player)

	return mgr
}

func (mgr *PlayerMgr) Run() {
}

func (mgr *PlayerMgr) GetPlayerByClientId(clientId int) *Player {
	return mgr.playerByClientId[clientId]
}

func (mgr *PlayerMgr) GetPlayerByPlayerId(playerId int64) *Player {
	return mgr.playerByPlayerId[playerId]
}

func (mgr *PlayerMgr) GetPlayerByUid(uid string) *Player {
	return mgr.playerByUid[uid]
}

func (mgr *PlayerMgr) RemovePlayer(playerId int64) {
	player, ok := mgr.playerByPlayerId[playerId]
	if ok {
		delete(mgr.playerByClientId, player.ClientId)
		delete(mgr.playerByUid, player.Uid)
		delete(mgr.playerByPlayerId, player.PlayerId)
	}
}

func (mgr *PlayerMgr) NewPlayer(uid, passWd string, clientId int, account *db.Account) (*Player, error) {
	player := CreatePlayer()
	//如果该玩家为新号则入库，如果不是新号则加载玩家数据
	playerId := account.PlayerId
	if playerId == 0 {
		player.PlayerId = db.InsertNewPlayer(uid, passWd)
		player.LastLoginTime = 0
		player.ClientId = clientId
		player.Uid = uid
		player.Init()
	} else {
		player.PlayerId = playerId
		player.Name = account.Name
		player.LastLoginTime = account.LastLoginTime
		player.ClientId = clientId
		player.Uid = account.Uid
		player.Load()
	}

	mgr.playerByClientId[player.ClientId] = player
	mgr.playerByPlayerId[player.PlayerId] = player
	mgr.playerByUid[player.Uid] = player
	return player, nil
}

func (mgr *PlayerMgr) KickOld(player *Player, newClientId int) {
	delete(mgr.playerByClientId, player.ClientId)
	service.Send("clientMgr", "kick", player.ClientId, message.KickReason_KICK_REASON_LOGIN_ELSEWHERE)
	player.ClientId = newClientId
	player.LastHeartbeat = time.Now().Unix()
	mgr.playerByClientId[newClientId] = player
}
