package file_cache

import (
	"encoding/json"
	"github.com/vrg0/go-common/logger"
	"net/http"
	"strings"
	"sync"
	"time"
)

/**
通过开关控制是否启用文件缓存，每次默认写入超过1分钟即关闭缓存
 */
type switcher struct {
	state  bool
	origin int64
	lock   sync.Mutex
}

func (s *switcher) turnOn() {
	s.lock.Lock()
	defer s.lock.Unlock()
	if !s.state { //打开状态，则关闭
		s.state = true
		s.origin = time.Now().Unix()
		create()
		senderDingDing()
	}
}

func (s *switcher) turnOff() {
	s.lock.Lock()
	defer s.lock.Unlock()
	if s.state {
		s.state = false
		s.origin = 0
		closed()
	}
}

func (s *switcher) status() bool {
	if s.state {
		current := time.Now().Unix()
		diff := current - s.origin
		if diff >= 60 {
			logger.Info("缓存切换")
			s.turnOff()
		}
	}
	return s.state
}

var cacheSwitcher *switcher
var alterMsg string

const (
	url         = "https://oapi.dingtalk.com/robot/send?access_token=9ffab8e4ae5f94e0fbf84aa91c9cb474d9e3d5bd0bb3c2daffe4cdfe0c2cbbc7"
	contentType = "application/json;charset=utf-8"
)

func init() {
	cacheSwitcher = &switcher{}
	alterMsg = buildDingDingMsg()
}

func Enabled() bool {
	return cacheSwitcher.status()
}

func OpenCache() {
	cacheSwitcher.turnOn()
}

func senderDingDing() {
	_, err := http.Post(url, contentType, strings.NewReader(alterMsg))
	if err != nil {
		logger.Error(err)
	}
}

func buildDingDingMsg() string {
	msg := dingDingMsg{
		MsgType: "text",
		Text: text{
			Content: "influxdb 写超时,已启用文件缓存",
		},
	}
	msgStr, err := json.Marshal(msg)
	if nil != err {
		logger.Error("无法序列化ding ding msg", err)
	}
	return string(msgStr)
}

type dingDingMsg struct {
	MsgType string
	Text    text
}

type text struct {
	Content string
}
