/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package dijjer.io.comm;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;
import dijjer.util.logging.Logger;

/**
 * @author ian
 * 
 * To change the template for this generated type comment go to Window - Preferences - Java - Code Generation - Code and
 * Comments
 */
public class MessageFilter {

	public static final String VERSION = "$Id$";
	private static final int DEFAULT_TIMEOUT = 10000;
	private boolean _matched = false;
	private HashSet _types = new HashSet();
	private HashMap _fields = new HashMap();
	private AbstractPeer _source;
	private Message _message;
	private final long _initialTimeout;
	private final long _timeout;
	private static Timer _removeTimer = new Timer(true);
	private static List _unclaimed = Collections.synchronizedList(new LinkedList());
	private static Set _filters = Collections.synchronizedSet(new TreeSet(new Comparator() {

		public int compare(Object o, Object o1) {
			return (int) (((MessageFilter) o)._timeout - ((MessageFilter) o1)._timeout);
		}
	}));

	private MessageFilter(long timeout, MessageType type) {
		if (type != null) {
			_types.add(type);
		}
		_initialTimeout = timeout;
		_timeout = System.currentTimeMillis() + timeout;
		if (timeout != -1) {
			Logger.debug("Adding filter: " + this + " to timeout in at " + _timeout + " ms.");
			synchronized (_filters) {
				_filters.add(this);
			}
			_removeTimer.schedule(new TimerTask() {

				private long start = System.currentTimeMillis();

				public void run() {
					synchronized (_filters) {
						if (_filters.remove(MessageFilter.this)) {
							Logger.debug("Timing out filter: " + MessageFilter.this + " at "
									+ (System.currentTimeMillis() - start) + " ms.");
						} else {
							Logger.debug("Removing used filter: " + MessageFilter.this + " at "
									+ (System.currentTimeMillis() - start) + " ms.");
						}
					}
					synchronized (MessageFilter.this) {
						MessageFilter.this.notify();
					}
				}
			}, timeout);
		}
	}

	private static MessageFilter create(MessageType type) {
		return new MessageFilter(-1, type);
	}

	public static MessageFilter create() {
		return new MessageFilter(-1, null);
	}

	public static MessageFilter create(long timeout) {
		return new MessageFilter(timeout, null);
	}

	public static MessageFilter create(long timeout, MessageType type) {
		return new MessageFilter(timeout, type);
	}

	public MessageFilter addType(MessageType type) {
		_types.add(type);
		return this;
	}

	public MessageFilter setSource(AbstractPeer source) {
		_source = source;
		return this;
	}

	public MessageFilter setField(String fieldName, boolean value) {
		return setField(fieldName, new Boolean(value));
	}

	public MessageFilter setField(String fieldName, byte value) {
		return setField(fieldName, new Byte(value));
	}

	public MessageFilter setField(String fieldName, short value) {
		return setField(fieldName, new Short(value));
	}

	public MessageFilter setField(String fieldName, int value) {
		return setField(fieldName, new Integer(value));
	}

	public MessageFilter setField(String fieldName, long value) {
		return setField(fieldName, new Long(value));
	}

	public MessageFilter setField(String fieldName, Object fieldValue) {
		synchronized (_fields) {
			_fields.put(fieldName, fieldValue);
		}
		return this;
	}

	public boolean match(Message m) {
		if (_matched) {
			return false;
		}
		if (!_types.isEmpty()) {
			if (!_types.contains(m.getSpec())) {
				return false;
			}
		}
		if ((_source != null) && (!_source.equals(m.getSource()))) {
			return false;
		}
		synchronized (_fields) {
			for (Iterator iter = _fields.keySet().iterator(); iter.hasNext();) {
				String fieldName = (String) iter.next();
				if (!m.isSet(fieldName)) {
					return false;
				}
				if (!_fields.get(fieldName).equals(m.getFromPayload(fieldName))) {
					return false;
				}
			}
		}
		_matched = true;
		return true;
	}

	public boolean matched() {
		if(!_matched) {
			synchronized (_unclaimed) {
				for (Iterator i = _unclaimed.iterator(); i.hasNext();) {
					Message m = (Message) i.next();
					if (match(m)) {
						setMessage(m);
						_unclaimed.remove(m);
						break;
					}
				}
			}
		}
		return _matched;
	}

	public synchronized Message getMessage() {
		return _message;
	}

	public synchronized void setMessage(Message message) {
		if (_message == null) {
			_message = message;
		} else {
			Logger.warning("Lost a message in MessageFilter.setMessage()!");
			return;
		}
		synchronized (_filters) {
			_filters.remove(this);
		}
		notify();
	}

	public String toString() {
		StringBuffer ret = new StringBuffer();
		ret.append("(");
		if (_types.isEmpty()) {
			ret.append("Any type");
		} else {
			for (Iterator i = _types.iterator(); i.hasNext();) {
				MessageType mt = (MessageType) i.next();
				ret.append(mt.getName());
				if (i.hasNext()) {
					ret.append(" or ");
				}
			}
		}
		if (!_fields.isEmpty()) {
			ret.append(" where ");
			for (Iterator i = _fields.entrySet().iterator(); i.hasNext();) {
				Map.Entry e = (Map.Entry) i.next();
				ret.append(e.getKey().toString() + "=" + e.getValue().toString());
				if (i.hasNext()) {
					ret.append(" and ");
				}
			}
		}
		ret.append(")");
		return ret.toString();
	}

	public static boolean checkFilters(Message message) {
		MessageFilter found = null;
		synchronized (_filters) {
			for (Iterator i = _filters.iterator(); i.hasNext();) {
				MessageFilter f = (MessageFilter) i.next();
				if (f.match(message)) {
					found = f;
					break;
				}
			}
		}
		if (found != null) {
			Logger.debug("Found matching filter for message: " + message);
			found.setMessage(message);
			return true;
		}
		return false;
	}

	public static void addUnclaimed(Message message) {
		_unclaimed.add(message);
		while (_unclaimed.size() > 1024) {
			_unclaimed.remove(0);
		}
	}

	public synchronized void match() {
		if (!matched()) {
			try {
				wait(_initialTimeout);
			} catch (InterruptedException e) {
			}
		}
	}
}