package kr.gmtc.gw.standstatus.component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import kr.gmtc.gw.comp.rest.vo.RestServiceData;
import kr.gmtc.gw.comp.thread.CustomThread;
import kr.gmtc.gw.standstatus.config.QueueManageBean;
import kr.gmtc.gw.standstatus.database.datasource2.IcSelectDao;
import kr.gmtc.gw.standstatus.database.dto.DataLoadDTO;
import kr.gmtc.gw.standstatus.database.dto.DataLoadHashMap;
import kr.gmtc.gw.standstatus.service.DataLoadService;
import kr.gmtc.gw.standstatus.vo.AiAnalyzeStandSttus;
import kr.gmtc.gw.standstatus.vo.AlarmMsgVO;
import kr.gmtc.gw.standstatus.vo.AlarmTargetVO;
import kr.gmtc.gw.standstatus.vo.AlarmVO;
import kr.gmtc.gw.standstatus.vo.AreaVO;

// @Component
// @DependsOn(value = {"serviceList"})
public class AnalysisAlarmStatus {
    
    private Logger logger;

   

    private final ObjectMapper objMapper = new ObjectMapper();
    
    private DataLoadDTO dto;
    private QueueManageBean queMB;

    // Queue<AlarmMsgVO> qAlamMsg; 
    // LinkedList<AlarmMsgVO> alamEndChkList;

    private LinkedBlockingQueue<AlarmMsgVO> qAlamMsg;
    private LinkedList<RestServiceData> serviceList;

    private LinkedList<AlarmMsgVO> alamEndChkList;
    private LinkedList<RestServiceData> standSttusList; 

    private DataLoadService ds;


	// private Map<Integer, LinkedList<RestServiceData>> serviceList;
    

    private CustomThread cThread_Analyze_Alarm_Start;
    private CustomThread cThread_Analyze_Alarm_End;
    

    public AnalysisAlarmStatus(){}

    public AnalysisAlarmStatus(DataLoadDTO dataLoadDTO, QueueManageBean queMB, DataLoadService ds){
        logger = LoggerFactory.getLogger(this.getClass());

        this.dto = dataLoadDTO;
        this.queMB = queMB;
        this.qAlamMsg = queMB.getQAlamMsg();
        this.serviceList = queMB.getServiceList();
        this.ds = ds;

        alamEndChkList = new LinkedList<AlarmMsgVO>();

        cThread_Analyze_Alarm_Start = new CustomThread("analysisAlarmStart", this, CustomThread.NO_SLEEP, this::analysis_Stand_sttus_alarm_start, null, false);
        cThread_Analyze_Alarm_End = new CustomThread("analysisAlarmEnd", this, CustomThread.NO_SLEEP, this::analysis_Stand_sttus_alarm_end, null, false);

    }

    public void start(){

        cThread_Analyze_Alarm_Start.start();
        cThread_Analyze_Alarm_End.start();

    }


    // 주기장 알림 상황 분석(상황시작)
    public void analysis_Stand_sttus_alarm_start() throws InterruptedException{

        if(serviceList.size() == 0 || dto.getDb_FltDep().size() == 0 ) {

            Thread.sleep(1000);
            return;
        } 


        for( DataLoadHashMap mapDep : dto.getDb_FltDep()){
            
            String sActStandOff = mapDep.getItemString("ACTL_STTAND_OFF_DT");
            String sPdcIsue = mapDep.getItemString("PDC_ISUE_TM");
            String sStandNo = mapDep.getItemString("STAND_NO");
            String sClsgn = mapDep.getItemString("CLSGN");

            if( !sActStandOff.equals("") && sPdcIsue.equals("")){

                setAlarmMsg(sStandNo, sClsgn, "1", "PDC발부 전 PushBack 진행중 입니다.");
                
            }

            
        }

        standSttusList = serviceList;

        for(int idx=0; idx<standSttusList.size(); idx++ ){
            AiAnalyzeStandSttus aiss = standSttusList.get(idx).getAiStandSttus();

            String sStandNo = standSttusList.get(idx).getStand_no();
            String sClsgn = standSttusList.get(idx).getClsgn();

            if(aiss.getPad_clear().equals("N") && standSttusList.get(idx).getAircraft_sttus_ty().equals("5") ){

                setAlarmMsg(sStandNo, sClsgn, "2", "Red-Zone내에 다른 차량 또는 사물이 있습니다.");

            }

        }

        Thread.sleep(1000);

    }


    private void setAlarmMsg(String sStandNo, String sClsgn, String sAlarmTy, String sAlarmMsg){

        int alarmYn = 0;
        for(int k=0; k<alamEndChkList.size(); k++){
            if(sStandNo.equals(alamEndChkList.get(k).getArea_id())){
                alarmYn = 1;
                break;
            }
        }

        if(alarmYn > 0) return;

        AlarmMsgVO alarmMsg = new AlarmMsgVO();
        alarmMsg.setAlarm_ty(sAlarmTy);
        alarmMsg.setAnals_ty("13");
        alarmMsg.setArea_type("AF03006");
        alarmMsg.setArea_id(sStandNo);
        alarmMsg.setTrgt_ty1("1");
        alarmMsg.setTrgt_id1(sClsgn);
        alarmMsg.setAnals_msg(sAlarmMsg);
        alarmMsg.setStart_end("Start");
        qAlamMsg.offer(alarmMsg);

    }

    // 주기장 알림 상황 분석(상황종료)
    public void analysis_Stand_sttus_alarm_end() throws InterruptedException{

        if( serviceList == null || serviceList.size() == 0 || alamEndChkList == null ||alamEndChkList.size() == 0 ) {

            Thread.sleep(1000);
            return;
        }

        // int alarmYn = 0;        
        // for(int k=0; k<alamEndChkList.size(); k++){
        //     if(mapDep.getItemString("STAND_NO").equals(alamEndChkList.get(k).getArea_id())){
        //         alarmYn = 1;
        //         break;
        //     }
        // }

        // if(alarmYn == 1) continue;

        for(int idx=0; idx<alamEndChkList.size(); idx++){
        //for( AlarmMsgVO chkAlarm : alamEndChkList){

            AlarmMsgVO chkAlarm = alamEndChkList.get(idx);

            int ChkCnt = 0;

            // PDC발부전 출발 상황 종료
            if(chkAlarm.getAlarm_ty().equals("1")){

                for( DataLoadHashMap mapDep : dto.getDb_FltDep()){

                    if(mapDep.get("STAND_NO").equals(chkAlarm.getArea_id())){
                        ChkCnt++;
                        if(!mapDep.get("PDC_ISUE_TM").equals("")){
                           chkAlarm.setStart_end("End");
                            qAlamMsg.offer(chkAlarm);
                            alamEndChkList.remove(idx);
                        }

                    }
                }
            }

            // Pad Clear ="N" 상황종료
            if(chkAlarm.getAlarm_ty().equals("2")){
                for(int idk=0; idk<standSttusList.size(); idk++ ){

                    AiAnalyzeStandSttus aiss = standSttusList.get(idk).getAiStandSttus();

                    if(chkAlarm.getArea_id().equals(standSttusList.get(idk).getStand_no()) ){

                        ChkCnt++;
                        if(aiss.getPad_clear().equals("Y")){
                            chkAlarm.setStart_end("End");
                            qAlamMsg.offer(chkAlarm);
                            alamEndChkList.remove(idx);
                        }
                    }

                }

            }

            // 주기장내 항공기 상태 종료
            if(ChkCnt == 0){

                chkAlarm.setStart_end("End");
                qAlamMsg.offer(chkAlarm);
                alamEndChkList.remove(idx);
                
            }



        }


        Thread.sleep(2000);

    }





    public String makeAlamMsg(){

        DataLoadHashMap svcheader = new DataLoadHashMap();
        DataLoadHashMap svcData = new DataLoadHashMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        Date now = new Date();
        
        svcheader.put("result_code", "200");
        svcheader.put("result_msg", "Success");

        svcData.put("header", svcheader);

        ArrayList arr = new ArrayList();
        String sJson = "";

        try {

            for (int idx=0; idx<qAlamMsg.size();idx++){

                AlarmMsgVO alarmMsg = qAlamMsg.poll();

                AlarmVO aVo = new AlarmVO();

                aVo.setAnals_id(ds.MakeAnalsId());
                aVo.setAnals_dt(sdf.format(now));
                aVo.setAnals_ty(alarmMsg.getAnals_ty());
                aVo.setStart_end(alarmMsg.getStart_end());

                AreaVO areaVO = new AreaVO();
                areaVO.setArea_type(alarmMsg.getArea_type());
                areaVO.setArea_id(alarmMsg.getArea_id());
                aVo.setArea(areaVO);

                AlarmTargetVO alarmTrgtVO = new AlarmTargetVO();
                alarmTrgtVO.setTrgt_ty(alarmMsg.getTrgt_ty1());
                alarmTrgtVO.setTrgt_id(alarmMsg.getTrgt_id1());
                aVo.setTarget1(alarmTrgtVO);

                alarmTrgtVO = new AlarmTargetVO();
                alarmTrgtVO.setTrgt_ty(alarmMsg.getTrgt_ty2());
                alarmTrgtVO.setTrgt_id(alarmMsg.getTrgt_id2());
                aVo.setTarget2(alarmTrgtVO);

                aVo.setAnals_msg(alarmMsg.getAnals_msg());

                arr.add(aVo);

                if(alarmMsg.getStart_end().equals("Start")) alamEndChkList.add(alarmMsg);

            }

            svcData.put("data", arr);

            sJson = objMapper.writeValueAsString(svcData);

        } catch (JsonProcessingException e) {
            logger.error(sJson, e);
        }

        return sJson;

    }

    


}
