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 com.fasterxml.jackson.databind.node.ObjectNode;

import kr.gmtc.tss.data.vo.TrackVO;
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<String> trackQueue;
	private boolean isRunning = true;
	private int listChunkSize = 100;
	private long sleepMillis;
	
	public DataLogger(Queue<String> trackQueue, int listChunkSize, long sleepMillis) {
		this.trackQueue = trackQueue; 
		this.listChunkSize = listChunkSize;
		this.sleepMillis = sleepMillis;
	}
	
	@Override
	public void run() {
		isRunning = true;
		
		while (isRunning) {
			try {
				String []  chunkArr = getChunkMessageArr(trackQueue);
				for (int i = 0; i < chunkArr.length; i++) {
					FileUtil.writeLogFile(getMessageBody(chunkArr[i]), MainServer.DATA_FILE_NAME);
				}
				
			} catch (Exception e) {
				logger.info("-- [SqlLogger] LogSave error : " +e.getLocalizedMessage());
			} 
			
			sleep(sleepMillis);
		}
	}
	
	private String [] getChunkMessageArr(Queue<String> trackQueue) {
		int loopCnt = 0;
		
		if(trackQueue.size()>listChunkSize) {
			loopCnt = listChunkSize;
		}else {
			loopCnt = trackQueue.size();
		}
		
		String [] chunkArr = new String[loopCnt];
		
		for (int i = 0; i < loopCnt; i++) {
			chunkArr[i] = trackQueue.poll();
		}
		
		return chunkArr;
	}

	private String getMessageBody(String str) {
		StringBuilder sb = new StringBuilder();

		sb.append(str);
		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;
	}
}