package kr.gmtc.gw.standstatus.controller;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

import kr.gmtc.gw.comp.rest.vo.RestServiceHeader;
import kr.gmtc.gw.comp.rest.vo.RestServiceVO;
import kr.gmtc.gw.comp.rest.vo.RestServiceData;
import kr.gmtc.gw.standstatus.utils.CmmnUtil;

@RestController
public class StandSttusServiceController {
    
    protected Logger logger;
    protected ObjectMapper mapper;

    @Resource(name = "serviceList")
	public Map<Integer, LinkedList<RestServiceData>> serviceList;

    @Resource(name = "serviceRunnig")
	private boolean serviceRunnig = false;
	
	@Value("${rest.service.queueCount}")
	private Integer scvQcount;

	@Value("${rest.service.serviceCount}")
	private Integer scvDatacount;

	@Resource(name = "testStandStsMap")
	HashMap<String, String> testStandStsMap;

	@Resource(name = "testStandStsMapAI")
	HashMap<String, String[]> testStandStsMapAI;

    private RestServiceVO restServiceVO;
    
    DateTimeFormatter dfPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    
    public StandSttusServiceController(){
        logger = LoggerFactory.getLogger(this.getClass());
		mapper = new ObjectMapper();
    }

    @GetMapping(value = "/getStandStatus/{qid}", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<String> getASDE( @PathVariable Integer qid) {
       
        int qidx = qid -1;
        String sRetJsonData = "";

        synchronized(serviceList.get(qidx)){
			sRetJsonData = makeServiceData(qidx, serviceList.get(qidx));
		}

        
        return ResponseEntity.ok(sRetJsonData);
    }


    private String makeServiceData(int queIdx, Queue<RestServiceData> procQue){

		String sendCode, sendMsg ;
		RestServiceHeader jsonHeader = new RestServiceHeader();
		List<RestServiceData> jsonData = new ArrayList<RestServiceData>();
		
		sendCode = "200";
		sendMsg = "----------------------------------------------------------------------------------------------------";
		
		restServiceVO = new RestServiceVO();
		
		int qTotalSize = procQue.size();
		int qSize = qTotalSize;

		if(qSize > scvDatacount) qSize = scvDatacount;

		if(queIdx > scvQcount -1 || queIdx < 0) {
			sendCode = "Err-01";
			sendMsg = "할당되지 않은 큐를 지정했습니다.";
			logger.error(sendMsg);
		}else {
			//if(procQue.peek() == null) {
			if(qSize <= 0) {
				sendCode = "200";
				sendMsg = "전송할 데이터 없음.";
				// logger.error("procQue size" + " / " + procQue.size());
			}else{

				serviceRunnig = true;

				while (qSize > 0 ) {

					RestServiceData data = procQue.poll();
					
					if( data != null){
						jsonData.add(data);
					}
					
					qSize--;
				}

				serviceRunnig = false ;
			}
			
		}
		
		jsonHeader.setResult_code(sendCode);
		jsonHeader.setResult_msg(sendMsg);
		
		restServiceVO.setHeader(jsonHeader);
		
		if (sendCode.equals("200")) {
			
			restServiceVO.setData(jsonData);

			logger.info("Que["+(queIdx + 1)+"] service count :" + jsonData.size() + "/" + qTotalSize);
		}
		
		String sRetJsonData = "";

		try {
			sRetJsonData = mapper.writeValueAsString(restServiceVO);
		} catch (JsonProcessingException e) {
			logger.error("[AsdeServiceController] makeServiceData-JsonProcessingException : " + CmmnUtil.getStatckTrace(e));
		}

		return sRetJsonData;

	}

	@RequestMapping(value={"setStandSts/{stadNo}/{sid}"}, method=RequestMethod.GET)
	public String setStandSts(@PathVariable String stadNo, @PathVariable String sid) throws Exception {
		
		String sStandNo, sSID ;
		String retValue = "";
		
		sStandNo = stadNo;
		sSID = sid;
		
		if(Integer.parseInt(sSID) < 1 || Integer.parseInt(sSID) > 8) {
			retValue = "Err: 주기장 상태의 범위는 1 ~ 6까지 입니다." ;
			return retValue;
		}
		
		testStandStsMap.put(sStandNo, sSID);
		
		for ( String stand : testStandStsMap.keySet() ) {
			retValue = retValue + "StandNO : " + stand +", Status : " + testStandStsMap.get(stand) + " <br>" ;
		}
		
		//gateStatusService.gateStatusSchedule();
		
		return retValue;
	}

	@RequestMapping(value={"setStandStsAI/{stadNo}/{sid}/{sAiSts}"}, method=RequestMethod.GET)
	public String setStandStsAI(@PathVariable String stadNo, @PathVariable String sid, @PathVariable String[] sAiSts) throws Exception {
		
		String sStandNo, sSID ;
		String retValue = "";
		String[] arrAiSts = {"N", "N", "N", "Y", "N"};
		
		sStandNo = stadNo;
		sSID = sid;
		
		if(sid.equals("0")){

		}else{
			if(Integer.parseInt(sSID) < 1 || Integer.parseInt(sSID) > 8) {
				retValue = "Err: 주기장 상태의 범위는 1 ~ 6까지 입니다." ;
				return retValue;
			}

			testStandStsMap.put(sStandNo, sSID);
			
			for ( String stand : testStandStsMap.keySet() ) {
				retValue = retValue + "StandNO : " + stand +", Status : " + testStandStsMap.get(stand) + " <br>" ;
			}

		}
		

		if(sAiSts == null ) sAiSts = arrAiSts;
		
		testStandStsMapAI.put(sStandNo, sAiSts);
		
		for ( String stand : testStandStsMapAI.keySet() ) {
			retValue = retValue + "AI Status StandNO : " + stand +", Status : " + Arrays.deepToString( testStandStsMapAI.get(stand)) + " <br>" ;
		}
		
		//gateStatusService.gateStatusSchedule();
		
		return retValue;
	}
	
	@GetMapping("/setTestClear")
	public String getStandStatus() throws Exception {
		
		testStandStsMap.clear();
		testStandStsMapAI.clear();
		//gateStatusService.gateStatusSchedule();
		
		return "Test Map Clear.";
	}

}
