package org.ctrip.ops.sysdev.filters;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

import org.apache.log4j.Logger;

import com.hubspot.jinjava.Jinjava;

public class BaseFilter implements Runnable {

	private static final Logger logger = Logger.getLogger(BaseFilter.class
			.getName());

	protected Map config;
	protected List<String> IF;
	protected ArrayBlockingQueue inputQueue;
	protected ArrayBlockingQueue outputQueue;
	protected Jinjava jinjava;

	public BaseFilter(Map config, ArrayBlockingQueue inputQueue) {
		this.config = config;
		this.IF = (List<String>) this.config.get("if");
		this.jinjava = new Jinjava();

		this.inputQueue = inputQueue;

		int queueSize = 1000;
		if (this.config.containsKey("queueSize")) {
			queueSize = (int) this.config.get("queueSize");
		}

		this.outputQueue = new ArrayBlockingQueue(queueSize, false);

		this.prepare();
	}

	protected void prepare() {
	};

	protected void filter(Map event) {
	};

	public void run() {
		while (true) {
			Map event = (Map) this.inputQueue.poll();
			if (event != null) {

				boolean succuess = true;
				if (this.IF != null) {
					for (String c : this.IF) {
						if (this.jinjava.render(c, event = event).equals(
								"false")) {
							succuess = false;
							break;
						}
					}
				}
				if (succuess == false) {
					continue;
				}

				this.filter(event);
				try {
					this.outputQueue.put(event);
				} catch (InterruptedException e) {
					logger.warn("put event to outMQ failed");
					logger.trace(e.getMessage());
				}
			}
		}
	}

	public ArrayBlockingQueue getOutputMQ() {
		return this.outputQueue;
	}

	public static void main(String[] args) {
		Jinjava jinjava = new Jinjava();
		long s = System.currentTimeMillis();
		final Map<String, Object> context = new HashMap();
		context.put("message", "Ja-red");
		context.put("@timestamp", 1442281327000L);

		Map event = new HashMap() {
			{
				put("event", context);
			}
		};

		for (int i = 0; i < 10000; i++) {
			jinjava.render("{{\"-\" in message}}", context);
		}
		System.out.println(System.currentTimeMillis() - s);

		System.out.println(jinjava.render(
				"{{event[\"@timestamp\"]|datetimeformat(\"%Y.%m\")}}",
				event = context));
	}
}

@@ -32,16 +32,44 @@
 lters;%0A%0A
+import java.util.ArrayList;%0A
 import j
@@ -1822,16 +1822,49 @@
 llis();%0A
+%09%09ArrayList a = new ArrayList();%0A
 %09%09final 
@@ -1908,16 +1908,16 @@
 hMap();%0A
-
 %09%09contex
@@ -1988,16 +1988,89 @@
 27000L);
+%0A%09%09context.put(%22array%22, new ArrayList() %7B%0A%09%09%09%7B%0A%09%09%09%09add(%22123%22);%0A%09%09%09%7D%0A%09%09%7D);
 %0A%0A%09%09Map 
@@ -2320,16 +2320,16 @@
 render(%0A
-
 %09%09%09%09%22%7B%7Be
@@ -2402,13 +2402,121 @@
 text));%0A
+%09%09System.out.println(jinjava.render(%0A%09%09%09%09%22%7B%7B%5C%22-%5C%22 in message && %5C%22X%5C%22 in message%7D%7D%22,%0A%09%09%09%09event = context));%0A
 %09%7D%0A%7D%0A

test &&