package com.evt.mgr;

import java.util.HashMap;
import java.util.Map;

import com.taurus.core.util.Logger;

public class EventReceiver {
	private final static String GROUP_EVT_KEY = "evt_group_";
	private final static String EVT_KEY = "event_";
	private final static String	EVT_DB_KEY		= "evt_db_";
	public final static String CHACHE_KEY = "group1_db8";

	Map<Integer, IHandler> handlerMap;
	volatile boolean run;

	public EventReceiver() {
		handlerMap = new HashMap<>();
	}

	void start() {
		run = true;
		for (int i = 0; i < 10; ++i) {
			new GroupRunnable(i, this, 1);
		}

		for (int i = 0; i < 10; ++i) {
			new GroupRunnable(i, this, 2);
		}
		
		for (int i = 0; i < 10; ++i) {
			new GroupRunnable(i, this, 3);
		}
	}

	void destroy() {
		run = false;
	}

	IHandler getHandler(int type) {
		IHandler handler = handlerMap.get(type);
		return handler;
	}

	private static final class GroupRunnable implements Runnable {
		private Logger log = Logger.getLogger(GroupRunnable.class);
		EventReceiver receiver;
		int type;
		int id;
		Thread thread;

		public GroupRunnable(int id, EventReceiver receiver, int type) {
			this.receiver = receiver;
			this.type = type;
			this.id = id;
			this.thread = new Thread(this, id + "");
			this.thread.start();
		}

		@Override
		public void run() {
			while (receiver.run) {
				int count=0;
				long startTime = System.currentTimeMillis();
				try {
					switch (type) {
					case 1:
						count = EventController.execEvt(GROUP_EVT_KEY + this.id, true);
						break;
					case 2:
						count = EventController.execEvt(EVT_KEY + id, false);
						break;
					case 3:
						count = EventController.execSql(EVT_DB_KEY+id);
						break;
					}

					long useTime = (System.currentTimeMillis() - startTime);
					if (count > 0)
					{
						EventServer.log.info("handle event:" + count + " use time:" + useTime + " ms");
					}
					if (useTime >= 30 || count >= 30)
					{
						Thread.sleep(1);
					}
					else if (count > 0){
						Thread.sleep(5);
					}
					else {
						Thread.sleep(20);
					}
				} catch (Exception e) {
					log.error(e);
				}
			}
		}

	}

}
