package game

import (
	"encoding/gob"
	"server/GoUtil"
	"server/game/mod/card"
	"server/game/mod/msg"
	"time"
)

type VarMgr struct {
	*ServerMod
}

type VarData struct {
	Var      map[string]interface{}
	ZeroTime int64
}

const (
	VAR_GOLD_CARD = "gold_card"
)

func (f *VarMgr) Init() {
	gob.Register(&VarGoldCard{})
	f.key = VAR_MGR_KEY
	f.data = &VarData{
		Var: make(map[string]interface{}),
	}
	// 注册处理函数
	f.init()
	if f.getData().Var == nil {
		f.getData().Var = make(map[string]interface{})
	}
	if f.getData().ZeroTime == GoUtil.ZeroTimestamp() {
		f.ZeroUpdate(&msg.Msg{})
	}
	f.RegisterHandler(msg.SERVER_ZERO_UPDATE, f.ZeroUpdate)
	f.mDispatr.AfterFunc(time.Duration(GoUtil.NextZeroTimestampDuration())*time.Second, func() {
		f.Send(&msg.Msg{
			Type: msg.SERVER_ZERO_UPDATE,
		})
	})
}

func (f *VarMgr) ZeroUpdate(m *msg.Msg) (interface{}, error) {
	f.getData().ZeroTime = GoUtil.ZeroTimestamp()
	// 随机生成两个金卡
	Card1, Card2 := card.RankGoldCard()
	f.SetVar(VAR_GOLD_CARD, &VarGoldCard{
		Four: Card1,
		Five: Card2,
	})
	return nil, nil
}

func (f *VarMgr) SetVar(key string, value interface{}) {
	f.getData().Var[key] = value
}

func (f *VarMgr) GetVar(key string) interface{} {
	return f.getData().Var[key]
}

func (f *VarMgr) DelVar(key string) {
	delete(f.getData().Var, key)
}

func (f *VarMgr) getData() *VarData {
	return f.data.(*VarData)
}
