package kr.gmtc.tss.filelog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Queue;

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

import com.fasterxml.jackson.databind.ObjectMapper;

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

public class MessageBodyLogger implements Runnable {

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

//	private String getMessageBody(String str) {
//		Date date = new Date();
//		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//		StringBuilder sb = new StringBuilder();
//		
//		sb.append(formatter.format(date));
//		sb.append(" ");
//		sb.append(str);
//		
//		return sb.toString();
//	}
	
	private String getMessageBody(TrackVO vo) {
		ObjectMapper mapper = new ObjectMapper();
		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;
	}
}