import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;
import javax.swing.Timer;
import java.awt.Container;
import java.awt.Insets;

public class Breakout extends JFrame implements ComponentListener, 
                                                ActionListener, WindowListener
{ private static final long serialVersionUID = 1L; 
  public static final int MIN_WIDTH = 280;
  public static final int MIN_HEIGHT = 425;
  private static final int TIMER_DELAY = 20; //millisec
  private Timer myTimer;
  private BreakoutDraw drawPanel;            // the panel to draw in
  private int turns = 0;
  private long startTimeMsec;


  public Breakout(int width, int height)
  { this.setTitle("Dumb Impervious Blocks");
    this.setBounds(0, 0, width, height);
    this.setVisible(true);
    
    Container contentPane = this.getContentPane();
    contentPane.setLayout(null);

    // add Draw Panel to JFrame
    drawPanel = new BreakoutDraw(this);
    contentPane.add(drawPanel);
    
    frameWasResized();
    this.addWindowListener(this);
    this.addComponentListener(this);
    startTimeMsec = System.currentTimeMillis();
    myTimer = new Timer(TIMER_DELAY, this);
    myTimer.start();
  }

  
  private void frameWasResized()
  { int width = this.getWidth();
    int height = this.getHeight();
    System.out.println(width+", " + height);
  
    if (width < MIN_WIDTH || height < MIN_HEIGHT) 
    { this.setSize(MIN_WIDTH,MIN_HEIGHT);
    }
    Insets inset = this.getInsets();

    int insideW = width - inset.left - inset.right;
    int insideH = height - inset.top - inset.bottom;
    drawPanel.setBounds(0, 0, insideW, insideH);
  }
  
  public void componentHidden(ComponentEvent e) {}
  public void componentMoved(ComponentEvent e) {} 
  public void componentShown(ComponentEvent e) {}
  public void componentResized(ComponentEvent e) 
  { frameWasResized();
  }
  
  public void windowActivated(WindowEvent arg0) {}
  public void windowClosed(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowOpened(WindowEvent e) {}
  public void windowClosing(WindowEvent e) 
  { long deltaMilliSeconds = System.currentTimeMillis() - startTimeMsec;
    System.out.println("Average Time Between Turns: "+deltaMilliSeconds/turns);
    System.exit(0);
  }

  public void actionPerformed(ActionEvent arg0)
  { if (arg0.getSource() == myTimer)
    { drawPanel.nextTurn();
      turns++;
    }
  }


  public static void main(String[] args)
  { new Breakout(500, 600);
  }

}
