package jp.ac.nii.icpc2010.manager;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.event.KeyListener;
import jp.ac.nii.icpc2010.display.AWTGameDisplay;
import jp.ac.nii.icpc2010.display.IGameDisplay;
import jp.ac.nii.icpc2010.playfield.PlayField;

public class DisplayManager extends Frame implements Runnable{

	private PlayField playField;
	private AWTGameDisplay gameDisplay;
	
	private OptionsManager om;

	public DisplayManager(String s, PlayField playField, OptionsManager om){
		super(s);

		this.playField = playField;
		this.om = om;

		this.gameDisplay = new AWTGameDisplay(this.playField, om);

		resizeWindow();
		//setResizable(false);

		add((Component)gameDisplay);
		
		String title = "JTron";
		if (om.getRedTitle() != null) {
			title += " / Red: " + om.getRedTitle();
		} 
		if (om.getBlueTitle() != null) {
			title += " / Blue: " + om.getBlueTitle();
		}
		
		setTitle(title);
		
		setVisible(true);
	}

	private void resizeWindow() {

		Insets insets = getInsets();
		Dimension d = ((AWTGameDisplay) gameDisplay).getDimension();

		int idealWidth = d.width + insets.left + insets.right;
		int idealHeight = d.height + insets.top + insets.bottom;

		setSize(idealWidth, idealHeight);
		this.playField.setNumOfComments(this.gameDisplay.getMaxNumOfComments());

		this.gameDisplay.reset();
	}

	@Override
	public void run() {

		while(true){
			if(this.playField.isDisplayResized()){
				this.playField.clearDisplayResized();
				resizeWindow();
			}

			this.gameDisplay.repaint();

			try {
				Thread.sleep(om.getDisplayInterval());
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.exit(1);
			}	
		}
	}

	public void addKeyListener(KeyListener listener){
		this.gameDisplay.addKeyListener(listener);
		super.addKeyListener(listener);
	}

	public void incrementCellWidth(){
		gameDisplay.setCellSize(gameDisplay.getCellWidth() + 1, gameDisplay.getCellHeight());
		resizeWindow();
	}
	public void incrementCellHeight(){
		gameDisplay.setCellSize(gameDisplay.getCellWidth(), gameDisplay.getCellHeight() + 1);
		resizeWindow();
	}
	public void decrementCellWidth(){
		gameDisplay.setCellSize(gameDisplay.getCellWidth() - 1, gameDisplay.getCellHeight());
		resizeWindow();
	}
	public void decrementCellHeight(){
		gameDisplay.setCellSize(gameDisplay.getCellWidth(), gameDisplay.getCellHeight() - 1);
		resizeWindow();
	}
}
