package net.mkonrad.synes.osc;

import java.net.SocketAddress;
import java.util.ArrayList;

import net.mkonrad.synes.gui.SceneCoreOSC;
import net.mkonrad.synes.util.DbgTools;
import net.mkonrad.synes.util.ErrTools;

import de.sciss.net.OSCListener;
import de.sciss.net.OSCMessage;

public class OSCMsgListener implements OSCListener
{
  private boolean _denyNonLocalhost;
  private ArrayList<OSCMsgProcessor> _processors;
  
  public OSCMsgListener(SceneCoreOSC coreCtrl, boolean denyNonLocalhost)
  {
    _denyNonLocalhost = denyNonLocalhost;
    _processors = new ArrayList<OSCMsgProcessor>();
  }
  
  public void addProcessor(OSCMsgProcessor proc)
  {
    _processors.add(proc);
  }
  
  public void removeProcessor(OSCMsgProcessor proc)
  {
    _processors.remove(proc);
  }

  public void messageReceived(OSCMessage msg, SocketAddress sender, long time)
  {
    if (_denyNonLocalhost && !sender.toString().startsWith("/127.0.0.1"))
    {
      DbgTools.print("Bad sender! " + sender.toString());
      return;
    }
    
    boolean handled = false;
    for (int i = 0; i < _processors.size(); i++)
    {
      if (_processors.get(i).canHandleOSCMsg(msg.getName()))
      {
        _processors.get(i).processOSCMsg(msg);
        handled = true;
      }
    }
    if (!handled)
      DbgTools.print("No OSCMsgProcessor for msg name: " + msg.getName());
  }  
}
