package base

import (
	"time"

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

/*
 计时器
*/

var ClockMgrSingleton = &ClockMgr{
	LastHour: -1,
	LastDay:  -1,
}

type ClockMgr struct {
	LastTime  time.Time
	LastMonth time.Month
	LastWeek  int
	LastDay   int
	LastHour  int
	LastMini  int
	LastSec   int
}

func (this *ClockMgr) ModuleName() string {
	return "ClockMgr"
}

func (this *ClockMgr) Init() {
	tNow := time.Now().Local()
	this.LastTime = tNow
	_, this.LastMonth, this.LastDay = tNow.Date()
	this.LastHour, this.LastMini, this.LastSec = tNow.Hour(), tNow.Minute(), tNow.Second()
	_, this.LastWeek = tNow.ISOWeek()
}

func (this *ClockMgr) Update() {
	tNow := time.Now().Local()
	sec := tNow.Second()
	if sec != this.LastSec {
		this.LastSec = sec
		// 秒
		PlayerMgrSingleton.OnSecondTimer()

		min := tNow.Minute()
		if min != this.LastMini {
			this.LastMini = min
			// 分
			PlayerMgrSingleton.OnMiniTimer()

			hour := tNow.Hour()
			if hour != this.LastHour {
				// 时
				ClientMgrSingleton.HourChange()

				this.LastHour = hour
				day := tNow.Day()
				if day != this.LastDay {
					// 天
					ClientMgrSingleton.DayChange()

					this.LastDay = day
					_, week := tNow.ISOWeek()
					if week != this.LastWeek {
						// 周

						this.LastWeek = week
					}
					month := tNow.Month()
					if month != this.LastMonth {
						// 月

						this.LastMonth = month
					}
				}
			}
		}
	}
}

func (this *ClockMgr) Shutdown() {
	module.UnregisteModule(this)
}

func init() {
	module.RegisteModule(ClockMgrSingleton, time.Millisecond*500, 0)
}
