package net.mkonrad.synes.ctrl;

import java.io.IOException;

import javax.media.j3d.Node;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;

import net.mkonrad.synes.data.SynthGraph;
import net.mkonrad.synes.data.SynthObj;
import net.mkonrad.synes.gui.elements.AbstractGraphLine;
import net.mkonrad.synes.synth.SynthExt;
import net.mkonrad.synes.util.ErrTools;

public class SynthLinePickingCtrl extends AbstractLinePickingCtrl
{

  public SynthLinePickingCtrl(CentralPickingCtrl pickCtrl)
  {
    super(pickCtrl);
  }
  
  public void removeGraph()
  {
    if (_selectedGraphLine == null)
      return;
    
    if (_coreCtrl.isOSCMode())
    {
      SynthGraph graph = (SynthGraph)_selectedGraphLine.getGraph();
      
      try
      {
        SynthObj synthObj;
        for (int i = 0; i < graph.size(); i++)
        {
          synthObj = graph.getSynthObj(i);
          
          if (synthObj.getSynth() != null)
          {
            synthObj.getSynth().release();
            synthObj.setSynth(null);
          }
        }
        
        graph.clear();
      }
      catch (IOException e)
      {
        ErrTools.print(e);
      }
    }
    
    _selectedGraphLine.getBG().detach();
    _coreCtrl.getCurrLayer().removeGraph(_selectedGraphLine.getGraph().getId());
    
    clearSelection();
  }

  public boolean clicked(Node pickedObj, Point3f where, int mouseState)
  {
    if (_pickCtrl.getState() == CentralPickingCtrl.STATE_GRAPH_CREATE)
    {
      return false;
    }
    else
    {
      makeSelection((AbstractGraphLine)pickedObj, where);
      
      if (((SynthGraph)_selectedGraphLine.getGraph()).getState() == SynthGraph.STATE_IMPRO
          && _pickCtrl.getMouseEvent().isControlDown())
      {
        playSynthGraph((SynthGraph)_selectedGraphLine.getGraph());
      }
    }
    
    return true;
  }

  public boolean dragged(Point3f where, int mouseState)
  {
    if (_selectedGraphLine == null)
      return true;
    
    SynthGraph graph = (SynthGraph)_selectedGraphLine.getGraph();
    
    try
    {
      for (int i = 0; i < graph.size(); i++)
      {
        if (graph.getSynthObj(i).getSynth() != null)
        {
          graph.getSynthObj(i).getSynth().modSynthSynth(graph.getModulator());
        }
      }
    }
    catch (IOException e)
    {
      ErrTools.print(e);
    }
    
    moveGraphLine(new Vector3f(where));
    
    return true;
  }

  public boolean released(Point3f where, int mouseState)
  {
    if (((SynthGraph)_selectedGraphLine.getGraph()).getState() == SynthGraph.STATE_IMPRO)
    {
      releaseSynthGraph((SynthGraph)_selectedGraphLine.getGraph());
    }
    
    clearSelection();
    
    return true;
  }

}
