package kr.gmtc.tss.data;

import java.util.Queue;

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

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

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

	Queue<AsdeTrackVO> asdeTrackQueue;
	Queue<AsdeTrackVO> asdeTrackLastQueue;
	private boolean isRunning = false;	
	private int batchInsertSize = 1000;
	
	BatchInsertManager batchInsertManager;
	private long sleepMillis;

	public DataInsertRunnable2(Queue<AsdeTrackVO> asdeTrackQueue, Queue<AsdeTrackVO> asdeTrackLastQueue, int batchInsertSize, BatchInsertManager batchInsertManager, long sleepMillis) {
		this.asdeTrackQueue = asdeTrackQueue;
		this.asdeTrackLastQueue = asdeTrackLastQueue;
		this.batchInsertSize = batchInsertSize;
		this.batchInsertManager = batchInsertManager;
		this.sleepMillis = sleepMillis;
	}
	
	@Override
	public void run() {
		isRunning = true;
		
		while (isRunning) {
			try {
				AsdeTrackVO [] chunkAsdeArr = getChunkAsdeArr(asdeTrackQueue);
				//AsdeTrackVO [] chunkAsdeLastArr = getChunkAsdeArr(asdeTrackLastQueue);
				if(isRunning) {
					if(chunkAsdeArr.length > 0) {
						batchInsertManager.insertAsdeData(chunkAsdeArr);
					}
					
//					라스트테이블 저장안함
//					if(chunkAsdeLastArr.length > 0) {
//						batchInsertManager.insertAsdeLastData(chunkAsdeLastArr);
//					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("[DataInsertRunnable2] Data Insert error : " ,e);
			} 
			
			sleep(sleepMillis);
		}
	}

	private AsdeTrackVO [] getChunkAsdeArr(Queue<AsdeTrackVO> sqlQueue) {
		int loopCnt = 0;
		if(sqlQueue.size() > batchInsertSize) {
			loopCnt = batchInsertSize;
		}else {
			loopCnt = sqlQueue.size();
		}
		
		AsdeTrackVO [] chunkArr = new AsdeTrackVO[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;
	}
}