package service

import (
	commonConfig "cicv-data-closedloop/aarch64/pji/common/config"
	commonService "cicv-data-closedloop/aarch64/pji/common/service"
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/domain"
	"cicv-data-closedloop/common/entity"
	"cicv-data-closedloop/common/util"
	"time"
)

// RunTimeWindowProducerQueue 将时间窗口内的包全部move出去，并等待当前时间窗口结束触发上传
func RunTimeWindowProducerQueue() {
	c_log.GlobalLogger.Info("生产者队列goroutine - 启动")
	for {
		// 收到自杀信号
		select {
		case signal := <-commonService.ChannelKillMove:
			if signal == 1 {
				commonService.ChannelKillMove <- 1
				if len(entity.TimeWindowProducerQueue) == 0 {
					commonService.AddKillTimes("4")
					return
				}
			} else { //signal == 2
				commonService.AddKillTimes("4")
				return
			}
		default:
		}

		// 处理
		time.Sleep(time.Duration(1) * time.Second)
		if len(entity.TimeWindowProducerQueue) > 0 {
			bags, _ := util.ListAbsolutePathWithSuffixAndSort(commonConfig.CloudConfig.BagDataDir, ".bag")
			currentTimeWindow := entity.TimeWindowProducerQueue[0]
			move := false
			bigger := false
			for _, bag := range bags {
				bagTime := util.GetBagTime(bag)
				// 2 如果bag不小于timeWindowBegin不大于timeWindowEnd，则移动
				compare1 := util.TimeCustom1GreaterEqualThanTimeCustom2(bagTime, currentTimeWindow.TimeWindowBegin)
				compare2 := util.TimeCustom1LessEqualThanTimeCustom2(bagTime, currentTimeWindow.TimeWindowEnd)
				if compare1 && compare2 {
					// 将bag包移动到Copy目录
					domain.MoveFromDataToCopy(currentTimeWindow.FaultTime, commonConfig.CloudConfig.BagDataDir, bag, commonConfig.CloudConfig.BagCopyDir)
					move = true
				} else {
					if util.TimeCustom1GreaterEqualThanTimeCustom2(bagTime, currentTimeWindow.TimeWindowBegin) {
						// 必须已经生成了窗口之后的包才算窗口结束了
						bigger = true
						break
					}
				}
			}
			// 如果没有包可以供当前窗口移动，且已经生成了更新的包，则当前窗口已经可以上传
			if !move && bigger {
				domain.SupplyCopyBags(commonConfig.CloudConfig.BagDataDir, commonConfig.CloudConfig.BagCopyDir, currentTimeWindow)
				// 将时间窗口移出准备队列
				entity.RemoveHeadOfTimeWindowProducerQueue()
				// 将时间窗口加入运行队列
				entity.AddTimeWindowToTimeWindowConsumerQueue(currentTimeWindow)
				continue
			}
		}
	}
}
