package main

import (
	"cicv-data-closedloop/pjisuv_ticker"
	"fmt"
	"math"
	"sync"
	"time"
)

var (
	Maxlenobj int32 = 0
)

// 定时任务触发器固定的
func Topic() string {
	return pjisuv_ticker.TickerTopic
}

// ******* 禁止存在下划线_
// 触发器标记
func Label() string {
	return "FrontVehiclesFrequentChangeLane"
}

func Rule(shareVars *sync.Map) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered from panic:", r)
		}
	}()
	// 1 使用goroutine
	go func(shareVars *sync.Map) {
		// 2 定义触发器的间隔时间
		ticker := time.NewTicker(time.Duration(4) * time.Second)
		defer ticker.Stop()
		// 3 运行一个无限循环
		for {
			select {
			// 定时器触发时执行的代码
			case <-ticker.C:
				FinalCallback(shareVars)

			}
		}
	}(shareVars)
}
func countChanges(slice [][]float32, AngularVelocityZOfCicvLocation float64) int {
	count := 0
lable1:
	for i := 0; i < len(slice[1]); {
		xi := slice[0][i]
		yi := math.Abs(float64(slice[1][i]))
		if (yi >= 1.8 || yi < 0.7) && xi >= 2 && math.Abs(AngularVelocityZOfCicvLocation) <= 1.6 {
			for j := 0; j < len(slice[1])-i-1; j++ {
				xij := slice[0][1+i+j]
				yij := math.Abs(float64(slice[1][1+i+j]))
				if ((yi >= 1.8 && yij <= 0.7) || (yi < 0.7 && yij >= 1.8)) && xij >= 2 && math.Abs(AngularVelocityZOfCicvLocation) <= 1.6 {
					count++
					//fmt.Println("here!!")
					i = i + j + 1
					continue lable1
				}
			}
			break lable1
		} else {
			i++
		}

	}
	return count
}
func FinalCallback(shareVars *sync.Map) {
	OutsideWorkshopFlag, ok := shareVars.Load("OutsideWorkshopFlag")
	ObjDicOfTpperception, ok1 := shareVars.Load("objDicOfTpperception")
	ObjDic := ObjDicOfTpperception.(map[uint32][][]float32)
	AngularVelocityZOfCicvLocation, _ := shareVars.Load("AngularVelocityZOfCicvLocation")
	AngularVelocityZ := AngularVelocityZOfCicvLocation.(float64)

	if ok && ok1 && OutsideWorkshopFlag.(bool) == true {
		for _, objValue := range ObjDic {
			Maxlenobj = max(Maxlenobj, int32(len(objValue[0])))
			if len(ObjDic[0]) <= 10 || countChanges(objValue, AngularVelocityZ) < 2 {
				continue
			}
			event_lable := "FrontVehiclesFrequentChangeLane"
			fmt.Println(event_lable)
			pjisuv_ticker.TickerChan <- pjisuv_ticker.TickInfo{FaultLabel: Label(), FaultHappenTime: pjisuv_ticker.GetNowTimeCustom()}
		}

		if Maxlenobj >= 100 {
			ObjDicOfTpperception = make(map[uint32][][]float32)
			shareVars.Store("ObjDicOfTpperception", ObjDicOfTpperception)
			Maxlenobj = 0
		}
	}

}