import javax.swing.*;
import java.io.*;
import java.awt.BorderLayout;

public class HWDisplay extends JApplet {
	static final long serialVersionUID = 42;
	static final String saveFile = "HoboWars.hws";
	public static ClassLoader cl;
	int speed = 10;
	HWMenu menu;
	HWMainDisplay gameDisplay;
	HWGameState gamestate;
	Thread t;
	public void init() {
		cl = this.getClass().getClassLoader();
		this.setLayout(new BorderLayout());
		menu = new HWMenu(this);
		changeTo(menu);
		gamestate = new HWGameState(this);
		add(gamestate, BorderLayout.PAGE_END);
//		pack();
		setVisible(true);
	}
	public void changeTo(HWMainDisplay comp){
		if (comp == gameDisplay)
			return;
		if (gameDisplay != null) {
			gameDisplay.stop();
			remove(gameDisplay);
		}
		gameDisplay = comp;
		add(gameDisplay, BorderLayout.PAGE_START);
		t = new Thread((Runnable)gameDisplay);
		validate();
//		pack();
		t.start();
	}
	public void changeTo(int levelNum) {
		gamestate.setLevel(levelNum);
		menu.introLevel(levelNum);
		changeTo(menu);
	}
	
	public void saveGame() {
		try {
			FileOutputStream fos = new FileOutputStream(saveFile);
			ObjectOutputStream out = new ObjectOutputStream(fos);
			out.writeObject(gamestate);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void loadGame() {
		try {
			FileInputStream fis = new FileInputStream(saveFile);
			ObjectInputStream in = new ObjectInputStream(fis);
			HWGameState gsTmp = (HWGameState)in.readObject();
			in.close();
			remove(gamestate);
			gamestate = gsTmp;
			add(gamestate, BorderLayout.PAGE_END);
			validate();
//			pack();
		} catch (IOException e) {
			gamestate.reset();
		} catch (ClassNotFoundException e) {
			gamestate.reset();
		}
		changeTo(gamestate.getLevel());
	}
	
	public static void main(String[] args) {
		new HWDisplay();
	}

}