package kr.gmtc.tss.data;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Queue;

import org.apache.ibatis.javassist.compiler.ast.Keyword;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import kr.gmtc.tss.data.vo.CctvTrackVO;

import kr.gmtc.tss.status.CountStatus;

public class ParseTargetRunnable implements Runnable {
	
	private boolean flagFile;
	private boolean flagDataBase;
	private boolean flagDataFile;
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	Queue<String> rcvQueue;
	Queue<CctvTrackVO> trackQueue;
	Queue<CctvTrackVO> trackLastQueue;
	Queue<String> dataFileQueue;
	Queue<CctvTrackVO> messageBodyQueue;
	
	private int rcvPos = 0;
	private int rcvStatic = 0;
	
	private boolean isRunning = false;	
	private int listChunkSize = 100; 
	private long sleepMillis;
	
	private String classification;
	private String swclassification;
	private String logclassification;

	public ParseTargetRunnable(Queue<String> rcvQueue, Queue<CctvTrackVO> trackQueue, Queue<CctvTrackVO> trackLastQueue
			, Queue<String> dataFileQueue,Queue<CctvTrackVO> messageBodyQueue, int listChunkSize
			, long sleepMillis, boolean flagFile, boolean flagDataBase, boolean flagDataFile
			, String classification, String swclassification, String logclassification) {
		this.rcvQueue = rcvQueue;
		this.trackQueue = trackQueue;
		this.trackLastQueue = trackLastQueue;
		this.dataFileQueue = dataFileQueue;
		this.messageBodyQueue = messageBodyQueue;
		this.listChunkSize = listChunkSize;
		this.sleepMillis = sleepMillis;
		this.flagFile = flagFile;
		this.flagDataBase = flagDataBase;
		this.flagDataFile = flagDataFile;
		this.classification = classification;
		this.swclassification = swclassification;
		this.logclassification = logclassification;
	}
	
	@Override
	public void run() {
		isRunning = true;
		
		while (isRunning) {
			try {
				
				int loopCnt = 0;
				if(rcvQueue.size()>listChunkSize) {
					loopCnt = listChunkSize;
				}else {
					loopCnt = rcvQueue.size();
				}
				String [] chunkArr = new String[loopCnt];
				
				for (int i = 0; i < loopCnt; i++) {
					chunkArr[i] = rcvQueue.poll();
				}
				
				for (int i = 0; i < chunkArr.length; i++) {
					parseAndEnqueue(chunkArr[i]);
				}
				
			} catch (Exception e) {
				if (e.getMessage() != null) {
					logger.debug("[ParseTarget] Parsing Error Message : " ,e);
				} else {
					logger.info("[ParserThread] Parsing Error Call Stack" ,e);
				}
			} 
			
			sleep(sleepMillis);
		}
	}
	
	private void parseAndEnqueue(String result) {
		try {
			ArrayList<CctvTrackVO> histroyQueue = new ArrayList<CctvTrackVO>();
			ObjectMapper mapper = new ObjectMapper();
			
			Map<String, Object> convert = mapper.readValue(result, new TypeReference<Map<String, Object>>() {});
			ArrayList<LinkedHashMap<String, Object>> list = (ArrayList<LinkedHashMap<String, Object>>) convert.get("data");
			// LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) convert.get("data");
			
			logger.info("수신 데이터 변환 건수 {}", list.size());
			
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
	        String dateTime = dateFormat.format(new Date());
			
	        StringBuilder sb = new StringBuilder();
			
	        sb.append(dateTime); sb.append(",");
	        sb.append(logclassification); sb.append(",");	//log구분
	        sb.append(swclassification); sb.append(",");	//sw구분
	        sb.append(classification); sb.append("|");		//서버구분
			int i = 0;
			int z = 0;
			for (LinkedHashMap<String, Object> map : list) {
				CctvTrackVO t = mapper.convertValue(map, CctvTrackVO.class);
				
				if(flagDataFile) {
					if (i > 0) sb.append("^");
					
					sb.append(t.getDtctTm());     sb.append(",");
					sb.append(t.getDtctCls());    sb.append(",");
					sb.append(t.getMtaTm());      sb.append(",");
					sb.append(t.getRwTm());       sb.append(",");
					// sb.append(t.getCcId());       sb.append(",");

					int j = 0;
					for (String k : t.getCcId()) {
						if (j > 0) sb.append("@"); 
						sb.append(k);
						j++;
					}
					sb.append(",");

					sb.append(t.getZnId());       sb.append(",");
					sb.append(t.getArcrftTp());   sb.append(",");
					sb.append(t.getArln());       sb.append(",");
					sb.append(t.getTrckId());     sb.append(",");
					// sb.append(t.getBbTlp());      sb.append(",");
					// sb.append(t.getBbBrp());      sb.append(",");
					// sb.append(t.getCrdFrm());     sb.append(",");
					// sb.append(t.getCrdGlbl());    sb.append(",");
					

					j = 0;
					for (String k : t.getBbTlp()) {
						if (j > 0) sb.append("@"); 
						sb.append(k);
						j++;
					}
					sb.append(",");
					
					j = 0;
					for (String k : t.getBbBrp()) {
						if (j > 0) sb.append("@"); 
						sb.append(k);
						j++;
					}
					sb.append(",");

					j = 0;
					for (String k : t.getCrdFrm()) {
						if (j > 0) sb.append("@"); 
						sb.append(k);
						j++;
					}
					sb.append(",");

					j = 0;
					for (String k : t.getCrdGlbl()) {
						if (j > 0) sb.append("@"); 
						sb.append(k);
						j++;
					}
					sb.append(",");

					sb.append(t.getDrctn());      sb.append(",");
					sb.append(t.getArcrftStnd()); sb.append(",");
					sb.append(t.getSpd()); 
				
				i++;
					
					// logger.info("logstash 포맷 변환 건수 {}", z++);
				}
				
				histroyQueue.add(t);
				i++;
			}
			
			
			if(flagFile) {
				messageBodyQueue.addAll(histroyQueue);
			}
			
			if(flagDataFile) {
				dataFileQueue.add(sb.toString());
			}
			
			if(flagDataBase) {
				if (histroyQueue.size() > 0) {
					trackQueue.addAll(histroyQueue);
				} 
				
//				if (flagDataBase) {
//					histroyQueue
//					.stream()
//					.collect(Collectors.groupingBy(TrackVO::getTargetId,           
//							Collectors.maxBy(Comparator.comparing(TrackVO::getReceptionDate))
//							)).forEach((key, value) -> {
//								trackLastQueue.add(value.get());
//							});;
//				}
			}
			
		} catch (Exception e) {
			logger.error("[ParserThread] Parsing Error Message : " + e.getMessage());
			
//			e.printStackTrace();
//			if (e.getMessage() != null) {
//				logger.debug("[ParserThread] Parsing Error Message : " + e.getMessage());
//				logger.debug("",e);
//			} else {
//				logger.debug("[ParserThread] Parsing Error Packet Message :" + result);
//			}
		}
	}

	
	public synchronized CountStatus getCountAndSetZero() {
		CountStatus countStatus = new CountStatus(rcvPos,rcvStatic);
		rcvPos = 0;
		rcvStatic = 0;
		return countStatus;
	}
	
	private void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			logger.debug("[ParseTargetRunnable] sleep error : "+e.getLocalizedMessage());
		}
	}

	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}
}
