package service

import (
	"cicv-data-closedloop/aarch64/kinglong/common/service"
	slaveConfig "cicv-data-closedloop/aarch64/kinglong/slave/package/config"
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/entity"
	"context"
	"encoding/json"
	"sync"
)

func PrepareTimeWindowProducerQueue() {
	var prepareTimeWindowProducerQueueMutex sync.Mutex
	ctx, cancel := context.WithCancel(context.Background())
	// 处理退出信号
	go func() {
		select {
		case signal := <-service.ChannelKillWindowProducer:
			if signal == 1 {
				cancel()
				slaveConfig.TcpListener.Close()
				service.AddKillTimes("3")
				return
			}
		}
	}()

	for {
		select {
		case <-ctx.Done():
			return
		default:
			conn, err := slaveConfig.TcpListener.Accept()
			if err != nil {
				select {
				case <-ctx.Done():
					return
				default:
					c_log.GlobalLogger.Error("接受连接错误:", err)
					continue
				}
			}
			prepareTimeWindowProducerQueueMutex.Lock()
			buffer := make([]byte, 2048)
			total, err := conn.Read(buffer)
			if err != nil {
				c_log.GlobalLogger.Error("读取数据错误:", err)
				continue
			}
			var timeWindow entity.TimeWindow
			err = json.Unmarshal(buffer[:total], &timeWindow)
			if err != nil {
				c_log.GlobalLogger.Error("解析Json时出错:", err)
				continue
			}
			entity.AddTimeWindowToTimeWindowProducerQueue(timeWindow)
			prepareTimeWindowProducerQueueMutex.Unlock()
		}

	}
}
