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

import com.tsi.comm.server.config.TsiCvimServerConfig;
import com.tsi.comm.server.process.AbstractTsiCvimProcess;
import com.tsi.comm.server.process.AbstractTsiCvimWorker;
import com.tsi.comm.server.process.packet.TsiCvimPacketWorker;
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.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 TsiCvimLoggingProcess extends AbstractTsiCvimProcess {

    private final TsiNodeManager nodeManager;

    private ExecutorService executor = null;
    private int qSize;

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

        this.workers = tsiCvimServerConfig.getLoggingWorkers();
        this.qSize = Math.max(10, this.nodeManager.size());
        if (this.workers == 1) {
            this.qSize *= 2;
        }
//        int nodeSize = Math.max(1, this.nodeManager.size());
//        int perQ = nodeSize / this.workers;

        this.executor = Executors.newFixedThreadPool(this.workers, new ThreadFactory() {
            private int count = 0;
            public Thread newThread(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++) {
            TsiCvimLoggingWorker loggingWorker = new TsiCvimLoggingWorker(ii, this.qSize);
            this.workerList.add(loggingWorker);
            this.executor.submit(loggingWorker); // 여기서 실행됨!
        }

//        for (int ii = 0; ii < this.workers; ii++) {
//            TsiCvimLoggingWorker loggingWorker = new TsiCvimLoggingWorker(ii, qSize);
//            this.workerList.add(loggingWorker);
//            Thread worker = new Thread(workerGroup, loggingWorker);
//            worker.setName(String.format("logWorker-%02d.%02d", this.workers, ii+1));
//            worker.setDaemon(true);
//            this.threadList.add(worker);
//        }
//        for (Thread worker : this.threadList) {
//            worker.start();
//        }
    }

    public boolean add(Object object, int idx) {
        boolean offer = false;
        AbstractTsiPacket packet = (AbstractTsiPacket)object;
        try {
            if (idx >= 0 && idx < this.workers) {
                offer = this.workerList.get(idx).add(packet);
            }
            else {
                log.error("LoggingProcess: Invalid logging queue index: {}", idx);
            }
        }
        catch (Exception e) {
            MDC.put("id", Long.toString(packet.getNodeId()));
            log.error("LoggingProcess: QUEUE_DATA.add: Exception: {}, {}", packet.getNodeId(), e.getMessage());
            MDC.clear();
        }
        return offer;
    }

    public void stop() {
        log.info("LoggingProcess Stopping...");

        for (AbstractTsiCvimWorker worker : this.workerList) {
            try {
                ((TsiCvimLoggingWorker) worker).getDATA_QUEUE().put(TsiCvimLoggingWorker.SHUTDOWN_PACKET);
            } catch (InterruptedException e) {
                log.warn("LoggingProcess: Interrupted while sending shutdown signal to worker {}.", worker.getIdx());
                Thread.currentThread().interrupt();
            }
        }

        this.executor.shutdown();

        try {
            if (!this.executor.awaitTermination(3, TimeUnit.SECONDS)) {
                this.executor.shutdownNow(); // 실행 중인 작업도 중단 시도

                // 큐에 남아있는 데이터 로깅
                int remainingTasks = 0;
                for (AbstractTsiCvimWorker worker : this.workerList) {
                    remainingTasks += ((TsiCvimPacketWorker) worker).getDATA_QUEUE().size();
                }
                if (remainingTasks > 0) {
                    log.warn("LoggingProcess: queue remain {}, forced shutdown.", remainingTasks);
                }

                // 강제 종료 후에도 종료될 때까지 조금 더 기다려줌
                if (!this.executor.awaitTermination(1, TimeUnit.SECONDS)) {
                    log.error("LoggingProcess: Executor did not terminate even after forced shutdown.");
                }
            }
        } catch (InterruptedException e) {
            this.executor.shutdownNow();
            Thread.currentThread().interrupt(); // 현재 스레드도 중단
        }

        log.info("LoggingProcess Stopped...");
    }

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