package kr.gmtc.tss.data;

import java.util.Queue;

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

import kr.gmtc.tss.data.vo.TrackVO;
import kr.gmtc.tss.db.BatchInsertManager; 

public class DataInsertRunnable implements Runnable {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	Queue<TrackVO> trackQueue;
	Queue<TrackVO> trackLastQueue;
	private boolean isRunning = false;	
	private int batchInsertSize = 1000;
	
	BatchInsertManager batchInsertManager;
	private long sleepMillis;
	private String topic;
	
	public DataInsertRunnable(Queue<TrackVO> trackQueue, Queue<TrackVO> trackLastQueue, int batchInsertSize, BatchInsertManager batchInsertManager, long sleepMillis, String topic) {
		this.trackQueue=trackQueue;
		this.trackLastQueue=trackLastQueue;
		this.batchInsertSize=batchInsertSize;
		this.batchInsertManager=batchInsertManager;
		this.sleepMillis=sleepMillis;
		this.topic=topic;
	}
	
	@Override
	public void run() {
		isRunning = true;
		
		while (isRunning) {
			try {
				TrackVO [] chunkTrackArr = getChunkTrackArr(trackQueue);
				// TrackVO [] chunkTrackLastArr = getChunkTrackArr(trackLastQueue);
				if(isRunning) {
					if(chunkTrackArr.length > 0) {
						batchInsertManager.insertTrackData(chunkTrackArr,topic);
					}
					
					/*
					 * if(chunkTrackLastArr.length > 0) {
					 * batchInsertManager.insertTrackLastData(chunkTrackLastArr); }
					 */
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("[DataInsertRunnable] Data Insert error : " ,e);
			} 
			
			sleep(sleepMillis);
		}
	}

	private TrackVO [] getChunkTrackArr(Queue<TrackVO> sqlQueue) {
		int loopCnt=0;
		if(sqlQueue.size()>batchInsertSize) {
			loopCnt=batchInsertSize;
		}else {
			loopCnt=sqlQueue.size();
		}
		
		TrackVO [] chunkArr = new TrackVO[loopCnt];
		
		for (int i = 0; i < loopCnt; i++) {
			chunkArr[i]=sqlQueue.poll();
		}
		return chunkArr;
	}

	private void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			logger.debug("[TargetManager] sleep error : " +e.getLocalizedMessage());
		}
	}

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