package net.mkonrad.synes.osc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.DatagramChannel;

import net.mkonrad.synes.util.DbgTools;
import net.mkonrad.synes.util.ErrTools;
import de.sciss.net.OSCMessage;
import de.sciss.net.OSCPacket;
import de.sciss.net.OSCTransmitter;

public class OSCMsgSender
{
  private SocketAddress _oscPeer;
  private OSCTransmitter _oscTrans;
  
  public OSCMsgSender(int peerPort, int sendingPort)
  {
    _oscPeer = new InetSocketAddress("127.0.0.1", peerPort);
    
    try
    {
      DatagramChannel udpChannelSend = DatagramChannel.open();
      udpChannelSend.socket().bind(new InetSocketAddress("127.0.0.1", sendingPort));
      _oscTrans = OSCTransmitter.newUsing(udpChannelSend);
    } catch (Exception e)
    {
      ErrTools.print(e);
    }
  }
  
  public void send(OSCPacket msg)
  {
    try
    {
      _oscTrans.send(msg, _oscPeer);
    }
    catch (IOException e)
    {
      ErrTools.print(e);
    }
  }
  
  public void sendOSCData(String msgName)
  {    
    OSCMessage msg = new OSCMessage(msgName, OSCMessage.NO_ARGS);
    send(msg);
  }
  
  public void sendOSCData(String msgName, Object data)
  {
    if (data == null)
      return;
    
    OSCMessage msg = new OSCMessage(msgName, new Object[] { data });
    send(msg);
  }
  
  public void sendOSCData(String msgName, Object[] data)
  {
    if (data == null)
      return;
    
    OSCMessage msg = new OSCMessage(msgName, data);
    send(msg);
  }
  
  public void sendOSCDataOneByOne(String msgName, Object[] data)
  {
    for (int i = 0; i < data.length; i++)
    {
      sendOSCData(msgName, data[i]);
    }
  }
  
}
