package com.zhiwei.manage.handle;

import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.zhiwei.manage.bean.FieldIntegerity;
import com.zhiwei.manage.util.Tools;

@Component
public class FieldThread extends Thread {

	private static boolean isrun = true;
	public static Map<String, FieldIntegerity> runMap = new ConcurrentHashMap<String, FieldIntegerity>();
	public static Queue<FieldIntegerity> queue = new LinkedBlockingQueue<FieldIntegerity>(500);
	private static final Log log = LogFactory.getLog(FieldThread.class);
	private static Lock fieldLock = new ReentrantLock();

	public FieldThread(){
		this.start();
	}
	
	public void stopMe() {
		isrun = false;
	}

	@Override
	public void run() {
		log.info("字段检测线程启动");
		while (isrun) {
			try {
				fieldLock.lock();
				Set<String> keys = runMap.keySet();
				for (Iterator<String> it = keys.iterator(); it.hasNext();) {
					String key = it.next();
					FieldIntegerity run = runMap.get(key);
					Calendar cal = Calendar.getInstance();
					if (run.getNextRun().before(cal.getTime()) && !run.isStartNow()) {
						queue.offer(run);
						cal.add(Calendar.HOUR, run.getFieldInterval());
						run.setNextRun(cal.getTime());
					}
				}
			} catch (Exception e) {
				log.info("字段线程异常,错误信息{}", e);
			} finally {
				fieldLock.unlock();
			}
			Tools.sleep(1000);
		}
	}
}
