package module

import (
	"github.com/goburrow/cache"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"sync"
	"time"
)

var (

	// PlayerCache缓存 key:uidKey, value:uid
	PlayerCache = cache.New(
		cache.WithMaximumSize(1000000),
		cache.WithExpireAfterAccess(10*time.Minute),
	)

	// 帐号缓存 key:accountName, value:AccountCache
	AccountCache = cache.New(
		cache.WithMaximumSize(1000000),
		cache.WithExpireAfterAccess(10*time.Minute),
	)

	mapCache = cache.New(
		cache.WithMaximumSize(10),
		cache.WithExpireAfterAccess(24*time.Hour),
	)
)

const (
	UserKeys    = "user_keys"
	AccountKeys = "account_keys"
)

var (
	lock         = &sync.RWMutex{}
	playerIdMap  = map[string]*models.Player{}
	accountIdMap = map[string]*models.Account{}
)

func BindPlayerId(player *models.Player) {
	if player == nil {
		return
	}
	lock.Lock()
	defer lock.Unlock()
	if a, ok := accountIdMap[player.OpenId]; ok {
		if a.IsNew {
			player.IsNew = true
		}
	}
	playerIdMap[player.OpenId] = player
}

func UnBindPlayerId(playerId string) {
	if playerId == "" {
		return
	}
	lock.Lock()
	defer lock.Unlock()
	delete(playerIdMap, playerId)
}

func BindAccountId(account *models.Account) {
	if account == nil {
		return
	}
	lock.Lock()
	defer lock.Unlock()
	if a, ok := accountIdMap[account.OpenId]; ok {
		if a.IsNew {
			account.IsNew = true
		}
	}
	accountIdMap[account.OpenId] = account
}

func UnBindAccountId(accountId string) {
	if accountId == "" {
		return
	}
	lock.Lock()
	defer lock.Unlock()
	delete(accountIdMap, accountId)

}
