package kr.gmtc.tss.data;

import java.util.Queue;

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

import kr.gmtc.tss.data.vo.AlarmVO;
import kr.gmtc.tss.data.vo.StandStatusVO;
import kr.gmtc.tss.db.BatchInsertManager; 

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

	Queue<StandStatusVO> standStatusQueue;
	Queue<AlarmVO> alarmQueue;
	
	private boolean isRunning = false;	
	private int batchInsertSize = 1000;
	
	BatchInsertManager batchInsertManager;
	private long sleepMillis;
	
	public DataInsertRunnable(Queue<StandStatusVO> standStatusQueue, Queue<AlarmVO> alarmQueue, int batchInsertSize, BatchInsertManager batchInsertManager, long sleepMillis) {
		this.standStatusQueue=standStatusQueue;
		this.alarmQueue=alarmQueue;
		this.batchInsertSize=batchInsertSize;
		this.batchInsertManager=batchInsertManager;
		this.sleepMillis=sleepMillis;
	}
	
	@Override
	public void run() {
		isRunning = true;
		
		while (isRunning) {
			try {
				StandStatusVO [] chunkStandStatusArr = getChunkStandStatuskArr(standStatusQueue);
				AlarmVO [] chunkAlarmtArr = getChunkAlarmArr(alarmQueue);
				
				if(isRunning) {
					if(chunkStandStatusArr.length > 0) {
						batchInsertManager.insertStandStatusData(chunkStandStatusArr);
					}
					
					if(chunkAlarmtArr.length > 0) {
						batchInsertManager.insertAlarmData(chunkAlarmtArr);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("[DataInsertRunnable] Data Insert error : " ,e);
			} 
			
			sleep(sleepMillis);
		}
	}

	private StandStatusVO [] getChunkStandStatuskArr(Queue<StandStatusVO> sqlQueue) {
		int loopCnt=0;
		if(sqlQueue.size()>batchInsertSize) {
			loopCnt=batchInsertSize;
		}else {
			loopCnt=sqlQueue.size();
		}
		
		StandStatusVO [] chunkArr = new StandStatusVO[loopCnt];
		
		for (int i = 0; i < loopCnt; i++) {
			chunkArr[i]=sqlQueue.poll();
		}
		return chunkArr;
	}
	
	private AlarmVO [] getChunkAlarmArr(Queue<AlarmVO> sqlQueue) {
		int loopCnt=0;
		if(sqlQueue.size()>batchInsertSize) {
			loopCnt=batchInsertSize;
		}else {
			loopCnt=sqlQueue.size();
		}
		
		AlarmVO [] chunkArr = new AlarmVO[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;
	}
}