package data

import (
	"time"

	"github.com/sirupsen/logrus"
)

var (
	stopServerNoticeEnd = "stopServerNoticeEnd"
)

type sentry struct {
	Name      string
	watcher   func(msgId, typ, content string) error // hook方法
	lastStamp int64
}

func SendToWorld(msgId, typ, content string) error {
	/*msgItem := msg.GmPlacard{
		MsgId:   msgId,
		Type:    typ,
		Content: content,
	}
	err := gate.SendToWorld(0, &msgItem)
	logrus.WithField("type", "SendToWorld").Infoln(msgItem, err)*/
	return nil
}

func (worker *sentry) Run() {
	for {
		time.Sleep(5 * time.Second) // 5秒扫描一次是否有需要通知的公告
		now := time.Now().Unix()
		worker.lastStamp = now
		for _, v := range Db {
			if v.EndAt < time.Now().Unix() || v.StartAt > time.Now().Unix() { // 如果最后时间小于当前时间，不执行了
				continue
			}

			// 如果间隔周期内执行过，那么跳过
			if v.LastInterval+v.Interval*60 < now {
				if worker.watcher != nil {
					if err := worker.watcher(v.MsgId, v.Type, v.Content); err != nil {
						logrus.WithField("worker", "sentry").Errorln(v, err.Error())
					} else {
						v.LastInterval = now
						v.UpdateAt = now
						// 保存到数据库中
						Db[v.MsgId] = v
					}

					if v.LastInterval+v.Interval*60 > v.EndAt { // 如果是最后一次发送消息, 给服务端发送一个特殊的消息
						if err := worker.watcher("", stopServerNoticeEnd, ""); err != nil {
							logrus.WithField("worker", "sentry").Errorln(v, err.Error())
						}
					}

				}
			}
		}
	}
}
