/// Evolver Copyright 2000, Morgan McGuire
/// matrix@alum.mit.edu   http://graphics3d.com/matrix
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.net.*;
import java.text.*;

/**
 * UI for an animation.
 */
public class AnimationEditor extends JFrame
{
  JPanel contents;
  JScrollPane scrollPane;

  Animation animation;
  ChunkDisplay chunkDisplay[];
  
  public AnimationEditor() 
  {
    contents = new JPanel();
    contents.setLayout(new BoxLayout(contents, BoxLayout.X_AXIS));

    animation = new Animation(21, Evolver.instance.geneticParameters);
    createDisplayForAnimation();

    scrollPane = new JScrollPane(contents,                                
                                 JScrollPane.VERTICAL_SCROLLBAR_NEVER,
                                 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    setContentPane(scrollPane);
    pack();
    setIconImage(new ImageIcon("evolver.gif").getImage());

    scrollPane.setPreferredSize(new Dimension(600, 200));

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    {
      final JFileChooser chooser = new JFileChooser();

      JMenu menu = new JMenu("File");
      menuBar.add(menu);
      JMenuItem open = new JMenuItem("Open...", KeyEvent.VK_O);
      menu.add(open);
      open.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            int retVal = chooser.showOpenDialog(AnimationEditor.this);
            if (retVal == JFileChooser.APPROVE_OPTION) {
              // Load
              animation.load(chooser.getSelectedFile(), Evolver.instance.geneticParameters);
              createDisplayForAnimation();
            }}});


      JMenuItem saveAs = new JMenuItem("Save As...", KeyEvent.VK_S);
      saveAs.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            int retVal = chooser.showSaveDialog(AnimationEditor.this);
            if (retVal == JFileChooser.APPROVE_OPTION) {
              // Save
              animation.save(chooser.getSelectedFile());
            }}});
      menu.add(saveAs);      
    }

    setTitle("Animation Editor");    
  }

  private void createDisplayForAnimation()
  {
    contents.removeAll();
    chunkDisplay = new ChunkDisplay[animation.numChunks()];
    for(int i = 0; i < chunkDisplay.length; i++) {
      chunkDisplay[i] = animation.getDisplay(i, this);
      contents.add(chunkDisplay[i]);
    }
    redisplayTimes();
    contents.revalidate();
  }


  /**
   * Forces all displays to update their timecode readout
   */
  public void redisplayTimes()
  {

    for(int i = 0; i < chunkDisplay.length; i++) {
      double time = animation.getStartTime(i);
      chunkDisplay[i].timeDisplay.setText(Animation.formatTime(time));
    }
  }
}
