package data

import (
	"encoding/json"
	"gadmin/internal/admin/forms"
	"gadmin/utility/character"
	"io/ioutil"
	"os"
	"sync"
	"time"

	"github.com/sirupsen/logrus"
)

type Notice struct {
	MsgId        string `json:"id"`
	Type         string `json:"type"`
	Content      string `json:"content"`
	CreateAt     int64  `json:"create_at"`
	UpdateAt     int64  `json:"update_at"`
	StartAt      int64  `json:"start_at"`
	EndAt        int64  `json:"end_at"`
	Interval     int64  `json:"interval"`
	LastInterval int64  `json:"last"`
}

var (
	Db = make(map[string]Notice)
	// once    sync.Once
	lock    sync.RWMutex
	bakFile = ""
)

func getBakFile() string {
	if bakFile != "" {
		return bakFile
	}
	bakFile = os.Getenv("STORAGE_NOTICE")
	return bakFile
}

func AddNotice(params forms.AddNoticeReq) *Notice {
	notice := Notice{
		Type:     params.Type,
		Content:  params.Content,
		StartAt:  params.StartAt,
		EndAt:    params.EndAt,
		Interval: params.Interval,
	}
	if params.MsgId != "" {
		notice.MsgId = params.MsgId
		notice.UpdateAt = time.Now().Unix()
	} else {
		data, _ := json.Marshal(notice)
		msgId := character.Md5Content(data)
		notice.MsgId = msgId
		notice.CreateAt = time.Now().Unix()
	}

	Db[notice.MsgId] = notice
	logrus.Infoln("Db :", Db)
	return &notice

}

func InitWorker() {
	worker := sentry{watcher: SendToWorld, Name: "sentry1"}
	go func() {
		worker.Run()
	}()

}

func SaveToBak() (err error) {
	lock.Lock()
	defer lock.Unlock()
	content, _ := json.Marshal(Db)
	err = ioutil.WriteFile(getBakFile(), content, 0666) //写入文件(字节数组)
	if err != nil {
		logrus.Panic("cannot Notices SaveToBak, err:" + err.Error())
	}
	return
}

func InitNotices() {
	go func() {
		// var err error
		for {
			time.Sleep(3 * time.Minute)
			if err := SaveToBak(); err != nil {
				logrus.Error("Notice SaveToBak err:", err)
				return
			}
		}
	}()

	go InitWorker()

	logrus.Info("start InitNotices...")
}

func LoadFromBak() (err error) {
	file, err := os.OpenFile(getBakFile(), os.O_RDONLY, 0666)
	if err != nil {
		return
	}
	content, err := ioutil.ReadAll(file)
	if err != nil {
		return
	}

	err = json.Unmarshal(content, &Db)

	logrus.Warnf("加载公告Db:%#v", Db)
	return
}
