package kr.gmtc.tss.filelog;

import java.util.Queue;

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

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

import kr.gmtc.tss.data.vo.AlarmVO;
import kr.gmtc.tss.data.vo.StandStatusVO;
import kr.gmtc.tss.main.MainServer;
import kr.gmtc.tss.util.FileUtil; 

public class DataLogger implements Runnable {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	// private Queue<TrackVO> trackQueue;
	
	private Queue<String> dataStandStatusFileQueue;
	private Queue<String> dataAlarmQueueFileQueue;
	
	private boolean isRunning = true;
	private int listChunkSize = 100;
	private long sleepMillis;
	
	public DataLogger(Queue<String> dataStandStatusFileQueue, Queue<String> dataAlarmQueueFileQueue, int listChunkSize, long sleepMillis) {
		this.dataStandStatusFileQueue = dataStandStatusFileQueue; 
		this.dataAlarmQueueFileQueue = dataAlarmQueueFileQueue;
		this.listChunkSize = listChunkSize;
		this.sleepMillis = sleepMillis;
	}
	
	@Override
	public void run() {
		isRunning = true;
		
		while (isRunning) {
			try {
				String []  chunkStatuskArr = getStatusChunkMessageArr(dataStandStatusFileQueue);
				for (int i = 0; i < chunkStatuskArr.length; i++) {
					FileUtil.writeLogFile(getMessageBody(chunkStatuskArr[i]), MainServer.DATA_STAND_FILE_NAME);
				}
				
				String []  chunkAlarmArr = getAlarmChunkMessageArr(dataAlarmQueueFileQueue);
				for (int i = 0; i < chunkAlarmArr.length; i++) {
					FileUtil.writeLogFile(getMessageBody(chunkAlarmArr[i]), MainServer.DATA_STAND_FILE_NAME);
				}
				
				
			} catch (Exception e) {
				logger.info("-- [SqlLogger] LogSave error : " +e.getLocalizedMessage());
			} 
			
			sleep(sleepMillis);
		}
	}
	
	private String [] getStatusChunkMessageArr(Queue<String> queue) {
		int loopCnt = 0;
		
		if(queue.size()>listChunkSize) {
			loopCnt = listChunkSize;
		}else {
			loopCnt = queue.size();
		}
		
		String [] chunkArr = new String[loopCnt];
		
		for (int i = 0; i < loopCnt; i++) {
			chunkArr[i] = queue.poll();
		}
		
		return chunkArr;
	}
	
	private String [] getAlarmChunkMessageArr(Queue<String> queue) {
		int loopCnt = 0;
		
		if(queue.size()>listChunkSize) {
			loopCnt = listChunkSize;
		}else {
			loopCnt = queue.size();
		}
		
		String [] chunkArr = new String[loopCnt];
		
		for (int i = 0; i < loopCnt; i++) {
			chunkArr[i] = queue.poll();
		}
		
		return chunkArr;
	}

	private String getMessageBody(Object vo) {
		StringBuilder sb = new StringBuilder();
		sb.append(vo.toString());
		sb.append("\n");
		return sb.toString();
	}
	
	private void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			logger.debug("[SqlLogger] sleep error : "+e.getLocalizedMessage());
		}
	}

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