package file_cache

import (
	"git.quantgroup.cn/DevOps/enoch/service/log"
	"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()
	}
}

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.Println("缓存切换")
			s.turnOff()
		}
	}
	return s.state
}

var cacheSwitcher *switcher

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

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

func OpenCache() {
	cacheSwitcher.turnOn()
}
