package com.szpg.plc.server;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.szpg.db.dao.PgAcuRdcmdDao;
import com.szpg.db.dao.impl.PgAcuRdcmdDaoImpl;
import com.szpg.plc.message.CommandResponse;
import com.szpg.util.Configure;

public class ACUCommandResponsePool {
	
	private final Logger logger = Logger.getLogger(this.getClass().getName()); //输出到message
	
	private Map<String, CommandResponse> responseList; // 响应队列
	
	private final int FRESH_MIN	= Integer.parseInt(Configure.getProperty("sys", "MESSAGEPOOL.REFRESH_TIME", "15")); //刷新时间
	
	public ACUCommandResponsePool() {
		responseList = new HashMap<String, CommandResponse>();
		
		// 启动定时刷新任务
		new ScheduledThreadPoolExecutor(1).scheduleAtFixedRate(new RefreshPoolTask(), 0, FRESH_MIN, TimeUnit.MINUTES);
	}
	
	public synchronized void putResponse(String key, CommandResponse message) {
		responseList.put(key, message);
		logger.debug("[++" + responseList.size() + "]" + key);
	}
	
	public synchronized CommandResponse getResponse(String key) {
		if (responseList.containsKey(key)) {
			CommandResponse cr = responseList.get(key);
			responseList.remove(key);
			
			logger.debug("[--" + responseList.size() + "]" + key);
			return cr;
		} else {
			return null;
		}
	}
	
	
	class RefreshPoolTask implements Runnable {
		
		PgAcuRdcmdDao cmdDao = new PgAcuRdcmdDaoImpl();
		
		@Override
		public synchronized void run() {
			cmdDao.deleteTimeoutCmd();
			
			logger.debug("清除数据库中的超时命令");
		}
	}
}


