package entity

import (
	"encoding/json"
	"sync"
	"time"
)

var (
	TimeWindowProducerQueue      []TimeWindow
	TimeWindowProducerQueueMutex sync.RWMutex

	TimeWindowConsumerQueue      []TimeWindow
	TimeWindowConsumerQueueMutex sync.RWMutex
	Subscriber0Time              = time.Date(2023, time.November, 23, 10, 30, 0, 0, time.UTC)
	Subscriber0TimeMutex         sync.Mutex
	Subscriber1Time              = time.Date(2023, time.November, 23, 10, 30, 0, 0, time.UTC)
	Subscriber1TimeMutex         sync.Mutex
	Subscriber2Time              = time.Date(2023, time.November, 23, 10, 30, 0, 0, time.UTC)
	Subscriber2TimeMutex         sync.Mutex
	Subscriber3Time              = time.Date(2023, time.November, 23, 10, 30, 0, 0, time.UTC)
	Subscriber3TimeMutex         sync.Mutex
	Subscriber4Time              = time.Date(2023, time.November, 23, 10, 30, 0, 0, time.UTC)
	Subscriber4TimeMutex         sync.Mutex
	Subscriber5Time              = time.Date(2023, time.November, 23, 10, 30, 0, 0, time.UTC)
	Subscriber5TimeMutex         sync.Mutex

	TcpSendTime      = time.Date(2023, time.November, 23, 10, 30, 0, 0, time.UTC)
	TcpSendTimeMutex sync.Mutex
)

type TimeWindow struct {
	FaultTime       string   `json:"FaultTime"`
	TimeWindowBegin string   `json:"TimeWindowBegin"`
	TimeWindowEnd   string   `json:"TimeWindowEnd"`
	Labels          []string `json:"Labels"`
	TriggerIds      []string `json:"TriggerIds"`
	Length          int      `json:"Length"`
	CanUpload       string   `json:"CanUpload"`
	MasterTopics    []string `json:"MasterTopics"`
	SlaveTopics     []string `json:"SlaveTopics"`
}

func RefreshTcpSendTime() {
	TcpSendTimeMutex.Lock()
	TcpSendTime = time.Now()
	TcpSendTimeMutex.Unlock()
}

func AddTimeWindowToTimeWindowProducerQueue(window TimeWindow) {
	TimeWindowProducerQueueMutex.RLock()
	{
		TimeWindowProducerQueue = append(TimeWindowProducerQueue, window)
	}
	TimeWindowProducerQueueMutex.RUnlock()
}

func AddTimeWindowToTimeWindowConsumerQueue(window TimeWindow) {
	TimeWindowConsumerQueueMutex.RLock()
	{
		TimeWindowConsumerQueue = append(TimeWindowConsumerQueue, window)
	}
	TimeWindowConsumerQueueMutex.RUnlock()
}

func RemoveHeadOfTimeWindowProducerQueue() {
	TimeWindowProducerQueueMutex.RLock()
	{
		TimeWindowProducerQueue = TimeWindowProducerQueue[1:]
	}
	TimeWindowProducerQueueMutex.RUnlock()
}

func RemoveHeadOfTimeWindowConsumerQueue() {
	TimeWindowConsumerQueueMutex.RLock()
	{
		TimeWindowConsumerQueue = TimeWindowConsumerQueue[1:]
	}
	TimeWindowConsumerQueueMutex.RUnlock()
}

// GetLastTimeWindow 获取最后一个时间窗口
func GetLastTimeWindow() *TimeWindow {
	var lastTimeWindow *TimeWindow // 获取最后一个时间窗口
	if len(TimeWindowProducerQueue) > 0 {
		lastTimeWindow = &TimeWindowProducerQueue[len(TimeWindowProducerQueue)-1]
	}
	return lastTimeWindow
}
func TimeWindowToJson(msg TimeWindow) (string, error) {
	jsonData, err := json.Marshal(msg)
	if err != nil {
		return "", err
	}
	return string(jsonData), nil
}
