/*
 * Copyright (C) 2003, C. Ramakrishnan / Auracle.
 * All rights reserved.
 *
 * This code is licensed under the BSD 3-Clause license.
 * See file LICENSE (or LICENSE.html) for more information.
 */

package com.illposed.osc.utility;

import com.illposed.osc.OSCBundle;
import com.illposed.osc.OSCListener;
import com.illposed.osc.OSCMessage;
import com.illposed.osc.OSCPacket;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Dispatches {@link OSCPacket}s to registered listeners.
 *
 * @author Chandrasekhar Ramakrishnan
 */
public class OSCPacketDispatcher {

	private final Map<String, OSCListener> addressToListener;

	public OSCPacketDispatcher() {
		this.addressToListener = new HashMap<String, OSCListener>();
	}

	/**
	 * Adds a listener that will then be notified of incoming messages.
	 * @param addressSelector addresses of incoming messages are checked
	 *   against this; you may use Java regular expressions here
	 * @param listener will be notified of incoming packets, if they match
	 */
	public void addListener(String addressSelector, OSCListener listener) {
		addressToListener.put(addressSelector, listener);
	}

	public void dispatchPacket(OSCPacket packet) {
		dispatchPacket(packet, null);
	}

	public void dispatchPacket(OSCPacket packet, Date timestamp) {
		if (packet instanceof OSCBundle) {
			dispatchBundle((OSCBundle) packet);
		} else {
			dispatchMessage((OSCMessage) packet, timestamp);
		}
	}

	private void dispatchBundle(OSCBundle bundle) {
		Date timestamp = bundle.getTimestamp();
		List<OSCPacket> packets = bundle.getPackets();
		for (OSCPacket packet : packets) {
			dispatchPacket(packet, timestamp);
		}
	}

	private void dispatchMessage(OSCMessage message, Date time) {
		for (Entry<String, OSCListener> addrList : addressToListener.entrySet()) {
			if (message.getAddress().matches(addrList.getKey())) {
				addrList.getValue().acceptMessage(time, message);
			}
		}
	}
}

@@ -1003,17 +1003,74 @@
 ons here
+ FIXME see the fix-me of %7B@link #matches(String, String)%7D
 %0A
-
 %09 * @par
@@ -1777,32 +1777,575 @@
 stamp);%0A%09%09%7D%0A%09%7D%0A%0A
+%09/**%0A%09 * Checks whether a OSC message address matches the given supplier.%0A%09 * The matching is currently done with Java regexp matching.%0A%09 * FIXME OSC standard requires wildcard matching (as in shell file-name matching, for example)%0A%09 * @param messageAddress for example %22/sc/mixer/volume%22%0A%09 * @param selector for example %22/sc/%5B%5E/%5D+/volume%22 or %22/sc/mixer/volume%22%0A%09 * @return true if the message matches the supplied selector%0A%09 */%0A%09private boolean matches(String messageAddress, String selector) %7B%0A%09%09return messageAddress.matches(selector);%0A%09%7D%0A%0A
 %09private void di
@@ -2474,16 +2474,24 @@
 %7B%0A%09%09%09if 
+(matches
 (message
@@ -2503,25 +2503,18 @@
 ddress()
-.matches(
+, 
 addrList

move address matching into a separate function