package domain

import (
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/entity"
	"cicv-data-closedloop/common/util"
	"strings"
	"time"
)

func MoveFromDataToCopy(faultTime string, bagDataDir string, sourceBag string, bagCopyDir string) {
	dir := GetCopyDir(bagCopyDir, faultTime)
	util.CreateDir(dir)
	targetBag := strings.Replace(sourceBag, bagDataDir, dir, 1)
	var copyCommand []string
	copyCommand = append(copyCommand, sourceBag)
	copyCommand = append(copyCommand, targetBag)
	_, _, _ = util.Execute("mv", copyCommand...)
	c_log.GlobalLogger.Infof("移动bag包 【%v】->【%v】", sourceBag, targetBag)
}

func GetCopyDir(bagDataDir string, faultTime string) string {
	return bagDataDir + faultTime + "/"
}

// SupplyCopyBags 如果 Copy目录下的包不够，则补充一些
func SupplyCopyBags(bagDataDir string, bagCopyDir string, currentTimeWindow entity.TimeWindow) {
	// 如果bag包没有达到length，补充几个
	copyBags, _ := util.ListAbsolutePathWithSuffixAndSort(GetCopyDir(bagCopyDir, currentTimeWindow.FaultTime), ".bag")
	copyBagsLength := len(copyBags)
	if copyBagsLength >= currentTimeWindow.Length {
		return
	}
	// 等待差距时间
	gap := currentTimeWindow.Length - copyBagsLength
	time.Sleep(time.Duration(gap) * time.Second)
	// 获取data目录下的包列表
	dataBags, _ := util.ListAbsolutePathWithSuffixAndSort(bagDataDir, ".bag")
	c_log.GlobalLogger.Info("故障 ", currentTimeWindow.FaultTime, "需要从data目录找回 ", gap, " 个 bag 包")
	for _, bag := range dataBags {
		bagTime := util.GetBagTime(bag)
		// 必须在区间内
		if util.TimeCustom1GreaterEqualThanTimeCustom2(bagTime, currentTimeWindow.FaultTime) {
			MoveFromDataToCopy(currentTimeWindow.FaultTime, bagDataDir, bag, bagCopyDir)
			gap = gap - 1
			if gap == 0 {
				break
			}
		}
	}
}
