package com.its.dsrc.process;

import com.its.app.AppUtils;
import com.its.dsrc.config.ThreadPoolInitializer;
import com.its.dsrc.dao.mapper.RseCtlrMapper;
import com.its.dsrc.dao.mapper.UnitSystMapper;
import com.its.dsrc.dao.mapper.batch.RseCtlrDao;
import com.its.dsrc.entity.*;
import com.its.dsrc.service.MultimediaService;
import com.its.dsrc.service.RseObuClctService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Slf4j
@RequiredArgsConstructor
@Service
public class DbmsDataProcess {

    private final LinkedBlockingQueue<DbmsData> DBMS_DATA_QUEUE = new LinkedBlockingQueue<>(1000);
    private final ThreadPoolExecutor taskExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);

    private final DbmsDataAsyncTask asyncTask;
    private final RseCtlrDao rseCtlrDao;

    private final UnitSystMapper unitSystMapper;
    private final RseCtlrMapper rseCtlrMapper;

    private final RseObuClctService rseObuClctService;
    private final MultimediaService multimediaService;

    int MAX_CORE = Runtime.getRuntime().availableProcessors();

    @PostConstruct
    void init() {
    }

    public void run() {
        log.info("DbmsDataProcess.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("DbmsDataProcess.Task: {}", ii);
            this.taskExecutor.execute(() -> {
                while (true) {
                    try {
                        DbmsData data = DBMS_DATA_QUEUE.take();
                        if (data != null) {
                            asyncTask.run(this, data);
                        }
                        else {
                            log.error("DbmsDataProcess.Task: Received data null");
                        }
                    }
                    catch (Exception e) {
                        log.error("DbmsDataProcess.Task: Exception: {}", e.getMessage(), e);
                    }
                }
            });
        }

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

    /**
     * 비동기 타스크에서 실행되는 함수.
     * 클래스가 달라야 비동기 타스크로 실행된다.
     * @param data
     */
    public void runJob(DbmsData data) {
        if (data.getType() == DbmsDataType.DBMS_DATA_UNIT_SYST_STTS) {
            TbUnitSystStts stts = (TbUnitSystStts) data.getData();
            this.unitSystMapper.updateUnitSystStts(stts);       // 상태정보 업데이트
            if (data.isHistory()) {
                this.unitSystMapper.insertUnitSystSttsHs(stts); // 상태정보 이력저장
            }
        }
        else {
            process(data);
        }
    }

    public void process(DbmsData data) {
        try {
            DbmsDataType type = data.getType();
            switch(type) {
                case DBMS_DATA_CTLR_STTS:
                    List<TbRseCtlrStts> ctlrSttsList = (List<TbRseCtlrStts>)data.getData();
                    this.rseCtlrDao.updateStts(ctlrSttsList, data.isHistory());
                    if (data.isHistory()) {
                        this.rseCtlrDao.insertStts(ctlrSttsList);
                    }
                    ctlrSttsList.clear();
                    break;
                case DBMS_DATA_OBU_GATHER_LOG:
                    List<TbRseObuClct> obuGatherInfos = (List<TbRseObuClct>)data.getData();
                    this.rseObuClctService.insertOBUGatherInfoHs(obuGatherInfos);
                    break;
                case DBMS_DATA_SECT_TRAF_HS:
                    List<TbRseSectTraf> sectTrafInfos = (List<TbRseSectTraf>)data.getData();
                    this.rseObuClctService.insertDsrcSectTraf(sectTrafInfos);
                    break;
                case DBMS_DATA_SECT_PASS_HS:
                    List<TbRseSectPassHs> sectPassInfos = (List<TbRseSectPassHs>)data.getData();
                    this.rseObuClctService.insertDsrcSectPassHs(sectPassInfos);
                    break;
                case DBMS_DATA_LOG_HS:
                    this.rseCtlrMapper.insertRseCtlrCnncHs((TbRseCtlrCnncHs)data.getData());
                    break;
                case DBMS_DATA_MULTIMEDIA_HS:
                    List<TbRseOffrSectTraf> dsrcOffrInfrHs = (List<TbRseOffrSectTraf>)data.getData();
                    this.multimediaService.insertDsrcOffrInfrHs(dsrcOffrInfrHs);
                    break;
                case DBMS_DATA_CTRL_HS:
                    this.rseCtlrMapper.insertRseCtrlHs((TbRseCtrlHs)data.getData());
                    break;
            }
        } catch (Exception e) {
            log.error("DbmsJobProcess.process: Exception: {}", e.toString());
        }
    }

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

}
