package rank

import (
	"math"
	"time"

	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/module"

	"mongo.games.com/game/model"
	"mongo.games.com/game/ranksrv/com"
)

var WinCoinMgrInstance = com.NewListMgr[*model.WinCoinInfo](
	func() int64 {
		return math.MaxInt32
	},
	func(platform string, index int32) ([]*model.WinCoinInfo, error) {
		// 每天21点刷新，获取前一天的排行
		startTs, endTs := StartEndTs()
		logger.Logger.Tracef("load wincoin platform:%s startTs:%v endTs:%v", platform, startTs, endTs)
		ret, err := model.FindWinCoinListTienlen(&model.FindWinCoinListArgs{
			Platform: platform,
			StartTs:  startTs,
			EndTs:    endTs,
		})
		return ret.List, err
	})

func StartEndTs() (startTs int64, endTs int64) {
	now := time.Now()
	year, month, day := now.Date()
	lastTs := time.Date(year, month, day, model.GameParamData.WinCoinUpdateTime, 0, 0, 0, now.Location())
	if now.Before(lastTs) {
		lastTs = lastTs.AddDate(0, 0, -1)
	}
	endTs = lastTs.Unix()
	return endTs - 24*int64(time.Hour.Seconds()), endTs
}

type WinCoinMgr struct {
}

func (w *WinCoinMgr) ModuleName() string {
	return "WinCoinMgr"
}

func (w *WinCoinMgr) Init() {
	for k := range com.PlatformConfigSingleton.Platforms {
		WinCoinMgrInstance.UpdateCache(k, 0)
	}
}

func (w *WinCoinMgr) Update() {
	h := time.Now().Hour()
	if h == model.GameParamData.WinCoinUpdateTime {
		for k := range com.PlatformConfigSingleton.Platforms {
			WinCoinMgrInstance.UpdateCache(k, 0)
		}
	}
}

func (w *WinCoinMgr) Shutdown() {
}

func init() {
	module.RegisteModule(new(WinCoinMgr), time.Hour, 0)
}
