/// 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.*;

/**
 * Base class for a component that can display an AnimationChunk.
 */
abstract class ChunkDisplay extends JPanel
{
  static final protected int frameWidth = 64;
  static final protected int frameHeight = 64;

  Animation animation;

  /**
   * Index of the chunk being displayed.
   */
  int index;

  /**
   * The enclosing editor.
   */
  AnimationEditor editor;

  JTextField durationEditor;
  JLabel timeDisplay;

  /**
   * Call this from your constructor, after your chunk index has been set.
   */
  protected void init(Component display, AnimationEditor editor)
  {
    this.editor = editor;
    this.animation = editor.animation;
    Color backColor = Color.white;

    timeDisplay = new JLabel("--");
    timeDisplay.setBackground(backColor);

    durationEditor = new JTextField("1");
    setDuration(1);
    durationEditor.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
          String s = durationEditor.getText();
          double duration = Double.parseDouble(s);
          if (duration != animation.getDuration(index)) {
            if ((duration <= 0) || (duration > 600)) {
              duration = 1;
            }
            setDuration(duration);
            ChunkDisplay.this.revalidate();
            ChunkDisplay.this.editor.redisplayTimes();
          }
        }
      });

    durationEditor.setBorder(BorderFactory.createLineBorder(Color.black, 1));
    setBackground(backColor);

    setLayout(new BorderLayout());
    JPanel displayPanel = new JPanel();
    displayPanel.setBackground(backColor);
    displayPanel.setLayout(new BoxLayout(displayPanel, BoxLayout.Y_AXIS));
    displayPanel.add(display);
    displayPanel.add(Box.createVerticalStrut(4));
    displayPanel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    add(timeDisplay, BorderLayout.NORTH);
    add(displayPanel, BorderLayout.CENTER);
    add(durationEditor, BorderLayout.SOUTH);
    setBorder(new CompoundBorder(BorderFactory.createLineBorder(Color.black, 1),
                                 new EmptyBorder(1,2,1,2)));
  }

  /**
   * Callback from the duration field editor.
   */
  void setDuration(double duration) 
  {
    int hsize = (int)(frameWidth + duration * 10);
    int vsize = frameHeight + 40;
    Dimension dims = new Dimension(hsize, vsize);
    setPreferredSize(dims);
    setMaximumSize(dims);
    setMinimumSize(dims);
    animation.setDuration(index, duration);
    durationEditor.setText("" + duration);
    revalidate();
  }
 
}
