package playermgr

import (
	"World/common"
	"World/db"
	"common/beegomap"
	"common/logger"
	"errors"
	_ "io/ioutil"
	//	"net"
	"sync"
)

var (
	players_map *beegomap.BeeMap //= make(map[int]*common.GamePlayer)
)

func init() {
	players_map = beegomap.NewBeeMap()
}

func GetPlayer(uid uint32) (*common.GamePlayer, common.ErrorType) {
	var player *common.GamePlayer = nil
	var err error
	for {
		player, err = GetPlayerFromMap(uid)
		if err == nil {
			return player, common.Error_OK
		}

		player, err = GetPlayerFromDB(int(uid))
		if player != nil && player.ConnLocker == nil {
			logger.Info("create player out channel uid:%v", uid)
			player.ConnLocker = new(sync.RWMutex)
			player.OutChannel = make(chan []byte, 32)
			player.OutDone = make(chan bool)
		}
		break
	}
	return player, common.Error_OK
}

func GetPlayerFromDB(uid int) (*common.GamePlayer, error) {
	player, err := db.LoadPlayerFromDB(uid)
	if err != nil {
		logger.Info("load from db error:%v for uid:%v", err, uid)
		return nil, err
	}

	players_map.Set(uint32(uid), player)
	logger.Info("GetPlayerFromDB-players_map.Set uid :%v", uid)

	return player, nil
}

func GetPlayerFromMap(uid uint32) (*common.GamePlayer, error) {
	vv := players_map.Get(uint32(uid))
	if vv != nil {
		player, _ := vv.(*common.GamePlayer)
		return player, nil
	}
	return nil, errors.New("not found uid")
}

func RemovePlayer(uid int) bool {
	players_map.Delete(uint32(uid))
	logger.Info("RemovePlayer players_map.Delete uid:%v", uid)
	return true
}

func GetPlayerRemarksFromDB(uid int) string {
	remarks := db.LoadPlayerRemarksFromDB(uid)

	return remarks
}

func InsertPlayerRemarksToDB(uid int32, data string) common.ErrorType {
	err := db.InsertPlayerRemarks(uid, data)

	if err != nil {
		return common.Error_DataBase_Failed
	}

	return common.Error_OK
}

func UpdatePlayerRemarksToDB(uid int32, data string) common.ErrorType {
	err := db.UpdatePlayerRemarks(uid, data)

	if err != nil {
		return common.Error_DataBase_Failed
	}

	return common.Error_OK
}
