package kr.gmtc.gw.dev.restdev.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

import kr.gmtc.gw.dev.restdev.service.StandMasterService;
import kr.gmtc.gw.dev.restdev.vo.AImetaTestVO;
import kr.gmtc.gw.dev.restdev.vo.AImetaTestVO.Data;
import kr.gmtc.gw.dev.restdev.vo.AiMetaVideoStatusVO;
import kr.gmtc.gw.dev.restdev.vo.AiMetaVideoStatusVO.AiMetaVideoStatusVO_Data;
import kr.gmtc.gw.dev.restdev.vo.AiMetaVideoStatusVO.AiMetaVideoStatusVO_Sts;
import kr.gmtc.gw.dev.restdev.vo.StandMasterVO;

@Component("restReciveController")
public class RestReciveController {
    
    
    private final RestTemplate restTemplate;

    private final ObjectMapper objectMapper;

    private Queue<AImetaTestVO> recvQ;

    private AiMetaVideoStatusVO mapStatus;

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

    @Autowired
    private StandMasterService standService;

    public RestReciveController() {

        this.restTemplate = new RestTemplate();

        this.objectMapper = new ObjectMapper();

        this.recvQ = new LinkedBlockingQueue<AImetaTestVO>();

        this.mapStatus = new AiMetaVideoStatusVO();
    }

    @Scheduled(fixedRate = 1000) // 1초마다 실행
    public void requestJsonData() {
        // JSON 데이터를 요청할 URL 설정
        String apiUrl = "http://localhost";
        String sPort = "18082";
        String sReqMsg = "getVideoTest"; 

        String sReqUrl = apiUrl + ":" +sPort + "/" + sReqMsg;

        // 요청을 보내고 JSON 데이터를 받아옴
        String jsonResponse = restTemplate.getForObject(sReqUrl, String.class);

        // 받아온 JSON 데이터를 Message 객체로 변환
        try {
            AImetaTestVO message = objectMapper.readValue(jsonResponse, AImetaTestVO.class);

            recvQ.offer(message);

            // 변환된 Message 객체를 원하는 방식으로 처리
            System.out.println("Received Message: " + message.toString());

        } catch (Exception e) {
            // JSON 파싱 오류 처리
            e.printStackTrace();
        }

        splitData();
    }


    private void splitData(){

        for(AImetaTestVO oneData : recvQ ){

            List<Data> recvDatas = oneData.getData();
            int iDataCnt = recvDatas.size();

            for(int idx=0; idx<iDataCnt; idx++ ){

                List<String> listCctvs = recvDatas.get(idx).getCc_id();
                int iCctvCnt = listCctvs.size();
                
                for(int idxC=0; idxC<iCctvCnt; idxC++){

                    // cctv_id <-> 주기장 번호 매핑
                    // MetaAIVideoStatus3 mapStatus3  = new MetaAIVideoStatus3();

                    String sCctvID = listCctvs.get(idxC);
                    String sStandNO = mappingStand(sCctvID);
                    String sSts = recvDatas.get(idx).getStts_cls();

                    AiMetaVideoStatusVO_Sts stsMap = mapStatus.getStsMap(sStandNO);

                    AiMetaVideoStatusVO_Data dataMap = mapStatus.getStsMap(sStandNO).getDataMap(sSts);

                    Map<String, AiMetaVideoStatusVO_Sts> standStsMap = new HashMap<String, AiMetaVideoStatusVO_Sts>();

                    
                    Date now = new Date();
                    
                    dataMap.setRecvTime( String.valueOf(sdf.format(now)));
                    dataMap.setStandNo(sStandNO);
                    dataMap.setSts(sSts);
                    
                    standStsMap.put(sStandNO, stsMap);

                    mapStatus.setMapStandNoGroup(standStsMap);

                
                }
            }
        }

    }

    private String mappingStand(String sCctvID){

        String sRetStandNo = "";

        List<StandMasterVO> standList = standService.getStandList();

        for(StandMasterVO standMaster : standList){
            if(standMaster.getCctvID().equals(sCctvID)){
                sRetStandNo = standMaster.getStandNO();
                return sRetStandNo;
            }

        }

        return sRetStandNo;
    }

    // private boolean checkExistMap(String sKey){
    //     boolean isEx = false;

    //     if(mapStatus.get(sKey) != null){
    //         isEx = true;
    //     }

    //     return isEx;

    // }


}
