package com.its.pis.process;

import com.its.app.AppUtils;
import com.its.pis.config.ThreadPoolInitializer;
import com.its.pis.dao.mapper.UnitSystMapper;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public abstract class AbstractMessageDataProcess {

    public static LinkedBlockingQueue<MessageData> DBMS_DATA_QUEUE = new LinkedBlockingQueue<>(1000);
    private UnitSystMapper unitSystMapper;
    private final ThreadPoolExecutor taskExecutor = (ThreadPoolExecutor)Executors.newFixedThreadPool(1);
    int MAX_CORE = Runtime.getRuntime().availableProcessors();

    @PostConstruct
    void init() {
        this.unitSystMapper = (UnitSystMapper) AppUtils.getBean(UnitSystMapper.class);
        postConstruct();
    }

    protected abstract void postConstruct();
    public abstract void process(DbmsJobData data);

    public void run() {
        log.info("AbstractMessageDataProcess.run: Start.");
        if (this.MAX_CORE < 8) {
            this.MAX_CORE = 8;
        }
        ThreadPoolInitializer poolInitializer = (ThreadPoolInitializer) AppUtils.getBean(ThreadPoolInitializer.class);
        int executePool = Math.max(this.MAX_CORE, poolInitializer.getWork());
        for (int ii = 0; ii < executePool; ii++) {
            log.info("AbstractMessageDataProcess.Task: {}", ii);
            this.taskExecutor.execute(() -> {
                while (true) {
                    try {
                        MessageData messageData = AbstractMessageDataProcess.DBMS_DATA_QUEUE.take();
                        if (messageData != null) {
                            //log.info("DBMS_DATA_QUEUE..take: {} EA, {}, {}", DBMS_DATA_QUEUE.size(), messageData, Thread.currentThread().getName());
                            MessageDataTask handler = (MessageDataTask) AppUtils.getBean(MessageDataTask.class);
                            handler.run(this, messageData);
                        }
                        else {
                            log.error("AbstractMessageDataProcess.Task: Received data null");
                        }
                    }
                    catch (Exception e) {
                        log.error("AbstractMessageDataProcess.Task: Exception: {}", e.getMessage(), e);
                    }
                }
            });
        }

        log.info("AbstractMessageDataProcess.run: ..End.");
    }

    /*
     *  작업큐에 데이터 추가
     */
    public boolean add(MessageData messageData) {
        boolean offer = false;
        try {
            //offer => full -> return
            //add   => full -> wait
            //큐가 차더라도 바로 리턴함.
            offer = AbstractMessageDataProcess.DBMS_DATA_QUEUE.offer(messageData);
            if (!offer) {
                log.error("MessageDataProcess.add: Queue Full Error, Size: {} EA", DBMS_DATA_QUEUE.size());
            }
        } catch (Exception e) {
            log.error("MessageDataProcess.add: Exception: {}", e.getMessage(), e);
        }
        return offer;
    }

    public static boolean addQ(MessageData messageData) {
        try {
            //offer => full -> return
            //add   => full -> wait
            //큐가 차더라도 바로 리턴함.
            if (!AbstractMessageDataProcess.DBMS_DATA_QUEUE.offer(messageData)) {
                log.error("AbstractMessageDataProcess.add: Queue Full Error, Size: {} EA, {}", DBMS_DATA_QUEUE.size(), messageData);
                return false;
            }
            log.info("DBMS_DATA_QUEUE.offer: {} EA, {}", DBMS_DATA_QUEUE.size(), messageData);
            return true;
        } catch (Exception e) {
            log.error("AbstractMessageDataProcess.add: Exception: {}", e.getMessage(), e);
        }
        return false;
    }

    public void runJob(MessageData messageData) {
//        if (dbmsJobData.getType() == DbmsJobType.DATA_TYPE_UNIT_SYST_STTS) {
//            TbUnitSystStts stts = (TbUnitSystStts)dbmsJobData.getData();
//            this.unitSystMapper.updateUnitSystStts(stts);       // 상태정보 업데이트
//            if (dbmsJobData.isHistory()) {
//                this.unitSystMapper.insertUnitSystSttsHs(stts); // 상태정보 이력저장
//            }
//        }
//        else {
//            process(dbmsJobData);
//        }
    }

}
