package com.tsi.comm.server.process.packet;

import com.tsi.comm.server.config.TsiCvimServerConfig;
import com.tsi.comm.server.kafka.KafkaProducerService;
import com.tsi.comm.server.process.AbstractTsiCvimProcess;
import com.tsi.comm.server.process.AbstractTsiCvimWorker;
import com.tsi.comm.server.protocol.AbstractTsiPacket;
import com.tsi.comm.server.repository.TsiNodeManager;
import com.tsi.common.spring.SpringUtils;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Slf4j
@Getter
@RequiredArgsConstructor
@Service
public class TsiCvimPacketProcess extends AbstractTsiCvimProcess {

    private final KafkaProducerService kafkaProducerService;
    private final TsiNodeManager nodeManager;
    private ExecutorService executor = null;
    private int qSize;

    public void start() {
        ThreadGroup workerGroup = new ThreadGroup("packetProcess");
        TsiCvimServerConfig tsiCvimServerConfig = SpringUtils.getBean(TsiCvimServerConfig.class);

        this.workers = tsiCvimServerConfig.getPacketWorkers();
        this.qSize = this.nodeManager.size();
        if (this.workers == 1) {
            this.qSize *= 3;
        }

        this.executor = Executors.newFixedThreadPool(this.workers, new ThreadFactory() {
            private int count = 0;
            public Thread newThread(@NotNull Runnable r) {
                Thread t = new Thread(workerGroup, r);
                t.setName(String.format("logWorker-%02d.%02d", workers, ++count));
                t.setDaemon(true);
                return t;
            }
        });

        for (int ii = 0; ii < this.workers; ii++) {
            TsiCvimPacketWorker packetWorker = new TsiCvimPacketWorker(ii, this.qSize, this.kafkaProducerService);
            this.workerList.add(packetWorker);
            this.executor.submit(packetWorker); // 여기서 실행됨!
        }
    }

    public boolean add(Object object, int idx) {
        boolean offer = false;
        AbstractTsiPacket packet = (AbstractTsiPacket)object;
        try {
            // TODO: 20251117: 통신연결시 할당된 패킷큐 인덱스로 바로 전송
//            idx = Math.abs(idx % this.workers);
            if (idx >= 0 && idx < this.workers) {
                offer = this.workerList.get(idx).add(packet);
            }
            else {
                log.error("Invalid packet queue index: {}", idx);
            }
        }
        catch (Exception e) {
            MDC.put("id", Long.toString(packet.getNodeId()));
            log.error("PacketProcess: QUEUE_DATA.add: Exception: {}, {}", packet.getNodeId(), e.getMessage());
            MDC.clear();
        }
        return offer;
    }

    public void stop() {
        log.info("PacketProcess Stopping...");
        this.executor.shutdown();
        try {
            if (!this.executor.awaitTermination(3, TimeUnit.SECONDS)) {
                this.executor.shutdownNow(); // 실행 중인 작업도 중단 시도
            }
        } catch (InterruptedException e) {
            this.executor.shutdownNow();
            Thread.currentThread().interrupt(); // 현재 스레드도 중단
        }
        log.info("PacketProcess Stopped...");
    }

    public void report() {
        for (AbstractTsiCvimWorker worker : this.workerList) {
            worker.report();
        }
    }
}
