import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.ImageIcon;

public class Controls extends JPanel implements Observer
{
  private Model model;
  private playSlider playback;
  private JButton play;
  private JButton rewind;
  private JButton reset;
  private JButton clear;

  // Bob the Builder this shit
  public Controls(Model model, Handler handler)
  {
    // Hook up this observer so that it will be notified when the model
    // changes.
    this.model = model;
    this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    this.setPreferredSize(new Dimension(1280,75));
    this.setMinimumSize(new Dimension(320, 75));
    //ImageIcon icon1 = new ImageIcon("/src/main/resources/playbutton.jpg");
    this.play = new JButton("Play");
    play.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        
      }
    });
    this.rewind = new JButton("Rewind");
    rewind.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        
      }
    });
    this.playback = new playSlider(0, 0, 0);
    playback.addChangeListener(new ChangeListener()
    {
      public void stateChanged(ChangeEvent e)
      {
        if (!playback.getSettingLen() && playback.getValue() != model.getTotalVisibleLen())
        {
          model.changeThingy(playback.getValue());
        }
      }
    });
    this.playback.setPreferredSize(new Dimension(280, 75));
    this.reset = new JButton("End");
    reset.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        model.ffwd();
        //playback.setValue(playback.getMaximum());
      }
    });
    this.clear = new JButton("Start");
    clear.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        model.rewind();
        //playback.setValue(playback.getMinimum());
      }
    });
    this.add(play);
    this.add(rewind);
    this.add(playback);
    this.add(clear);
    this.add(reset);
    model.addObserver(this);
  }

  public void update(Object observable)
  {
    int len = model.getTotalLen();
    if (len > 0)
    {
      playback.toggleSettingLen();
      playback.setMaximum(len);
      playback.toggleSettingLen();
      playback.setValue(model.getTotalVisibleLen());
    }
    this.setBackground(model.controlColour);
    revalidate();
    repaint();
  }
}

class playSlider extends JSlider
{
  private boolean settingLen;
  
  public playSlider(int min, int max, int val)
  {
    super(min, max, val);
    this.settingLen = false;
  }
  
  public void toggleSettingLen()
  {
    this.settingLen = !settingLen;
  }

  public boolean getSettingLen()
  {
    return settingLen;
  }
}
