package net.mkonrad.synes.synth;

import java.io.IOException;

import javax.vecmath.Point3f;

import de.sciss.jcollider.Group;
import de.sciss.jcollider.Node;
import de.sciss.jcollider.Server;
import de.sciss.jcollider.Synth;
import de.sciss.net.OSCBundle;
import de.sciss.net.OSCMessage;
import net.mkonrad.synes.data.IdCounter;
import net.mkonrad.synes.data.Modulator;
import net.mkonrad.synes.data.SeqInstrument;
import net.mkonrad.synes.data.SynthInstrument;
import net.mkonrad.synes.data.SynthObj;
import net.mkonrad.synes.gui.SceneCoreOSC;
import net.mkonrad.synes.util.DbgTools;
import net.mkonrad.synes.util.ErrTools;

public class SynthExt extends Synth
{  
  private SynthObj _synthObj;
  private Group _group;

  public SynthExt(Server server, Group group, SynthObj synthObj) throws IOException
  {
    super(synthObj.getInstrumentSymbol(), server, IdCounter.NODE_IDS++);
    _group = group;
    _synthObj = synthObj;
  }
  
  static public SynthExt basicNew(Server server, Group group, SynthObj synthObj)
    throws IOException
  {
    return new SynthExt(server, group, synthObj);
  }
  
  public SynthObj getSynthObj()
  {
    return _synthObj;
  }
  
  public void play()
    throws IOException
  {
    play(0, new String[] { }, new float[] { });
  }

  public void play(String[] inputParams, float[] inputValues)
    throws IOException
  {
    play(0, inputParams, inputValues);
  }
  
  public void play(int ms, String[] inputParams, float[] inputValues)
    throws IOException
  {
    //DbgTools.print("Playing instrument " + _synthObj.getInstrumentSymbol());
    
    OSCMessage newMsg = addToTailMsg(_group, inputParams, inputValues);
    
    getServer().sendBundle(createBundle(ms, newMsg));
  }
  
  public void releaseWithin(int ms)
    throws IOException
  {
    OSCMessage releaseMsg = releaseMsg();
    
    getServer().sendBundle(createBundle(ms, releaseMsg));
  }
    
  private OSCBundle createBundle(long ms, OSCMessage msg)
  {
    OSCBundle bndl = new OSCBundle(System.currentTimeMillis() + ms + 50); //default delay of 50ms
    bndl.addPacket(msg);
    
    return bndl;
  }

  public void modSeqSynth(Point3f intercept) throws IOException
  {
    set(_synthObj.getInstrument().getModArgs(), ((SeqInstrument)_synthObj.getInstrument()).getAllModValues(intercept));
  }
  
  public void modSynthSynth(Modulator mod) throws IOException
  {
    set(_synthObj.getInstrument().getModArgs(), ((SynthInstrument)_synthObj.getInstrument()).getAllModValues(_synthObj, mod));
  }
}
