package com.yeejoin.amos.supervision.business.trigger;

import com.yeejoin.amos.supervision.context.IotContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class TriggerKeyQueue {
	/**
     * 日志记录器
     */
	private static final Logger log = LoggerFactory.getLogger(TriggerKeyQueue.class);

	/**
	 * 单例
	 */
	private static volatile TriggerKeyQueue instance;

	/**
	 * 队列
	 */
	private static final BlockingQueue<HashMap<String,Object>> blockingQueue = new LinkedBlockingQueue<HashMap<String,Object>>();

	/**
	 * 控制消费者线程运行状态
	 */
	private static boolean isRunning = true;

	/**
	 * 构造方法
	 */
	private TriggerKeyQueue() {
		
	}

	/**
	 * 获取单例
	 * 
	 * @return
	 */
	public static TriggerKeyQueue getInstance() {
		if (instance == null) {
			synchronized (TriggerKeyQueue.class) {
				if (instance == null) {
					instance = new TriggerKeyQueue();
				}
			}
		}
		return instance;
	}

	/**
	 * 添加数据
	 * 
	 * @param frame
	 */
	public void add(HashMap<String,Object> keyMap) {
		while (blockingQueue.add(keyMap)) {
			log.debug("add a keyMap into blockingQueue successful!");
			break;
		}
	}

	public void start() {
		Thread thread = new Thread(new TriggerKeyConsumer(), "trigger consumer thread");
		thread.start();
	}

	/**
	 * 消费者线程
	 * 
	 * @author as-suhg
	 *
	 */
	class TriggerKeyConsumer implements Runnable {

		/**
		 * 1.从队列中取出数据；2.调用业务接口；
		 */
		@Override
		public void run() {
			while (isRunning) {
				// 1.从队列中取出数据
				HashMap<String,Object> keyMap = new HashMap<String,Object>();
				try {
					keyMap = blockingQueue.take();
				} catch (InterruptedException e) {
					log.error(e.getMessage(),e);
				}
				// 2.调用业务接口；
				if (keyMap == null||keyMap.isEmpty()) {
					log.warn("keyMap is empty!");
				} else {
					try {
						ITriggerDataService triggerDataService = (ITriggerDataService) IotContext.getInstance().getBean(("triggerDataService"));
						triggerDataService.process(keyMap);									
					} catch (Exception e) {
						log.error(e.getMessage(),e);
						// 失败处理
					}
				}
			}
		}

	}




}
