package service

import (
	"cicv-data-closedloop/aarch64/pji/common/config"
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/util"
	"time"
)

// BagCacheClean 保证本地缓存的包数量不超过设定值
func BagCacheClean() {
	c_log.GlobalLogger.Info("启动清理缓存的 goroutine 维护目录【", config.CloudConfig.BagDataDir, "】的 bag 包数量：", config.CloudConfig.BagNumber)
	for {
		// 收到自杀信号
		select {
		case signal := <-ChannelKillDiskClean:
			if signal == 1 {
				AddKillTimes("2")
				return
			}
		default:
		}

		// 1 ------- 每10秒清理一次 -------
		time.Sleep(time.Duration(10) * time.Second)
		// 2 ------- 获取目录下所有bag包 -------
		bags, _ := util.ListAbsolutePathWithSuffixAndSort(config.CloudConfig.BagDataDir, ".bag")
		// 3 如果打包数量超过n个，删除最旧的包{
		if len(bags) > config.CloudConfig.BagNumber {
			diff := len(bags) - config.CloudConfig.BagNumber
			for i := 0; i < diff; i++ {
				_ = util.DeleteFile(bags[i])
			}
		}
	}
}
