package de.tu_darmstadt.tk.SmartHomeNetworkSim.view;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;

import javax.swing.JFrame;

import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.util.Utility;

/**
 * Main class of the GUI, which combines the UserInterface and visualization of the simulation.
 *
 * @author Andreas T. Meyer-Berg
 */
@SuppressWarnings("serial")
public class MainFrame extends JFrame {
	/**
	 * Controller for manipulation of the model
	 */
	private Controller controller;
	/**
	 * MenuBar of the GUI
	 */
	private MenuBar menu;
	/**
	 * Panel which visualizes the devices, connections and links
	 */
	public final VisualizationPanel panel; 
	/**
	 * Creates a new Frame for the program, which is the most outer frame of the application
	 * @param c Controller which handles the user interaction
	 */
	public MainFrame(Controller c) {
		//Set and control
		this.controller = c;
		
		setTitle("Smart Home Network Simulator");	
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setIconImage(Utility.loadFile("images/smartHome_icon.png"));
		setLayout(new FlowLayout());
		
		//Set initial size of the frame
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		int width = screenSize.width; 
		int height = screenSize.height;
		this.setBounds(width/8, height/8, 6*width/8, 6*height/8);
		this.setMinimumSize(new Dimension(640, 480));
		
		/*
		 * Add Visualization Panel
		 */
		//Could be a more complex panel later on (TabbedPanel, ScrollPanel, SplitPanel
		panel = new VisualizationPanel(controller);
		this.setContentPane(panel);
		c.addObserver(panel);
		
		/*
		 * Add Menu Bar
		 */
		menu = new MenuBar(controller);
		super.setJMenuBar(menu);
		
		//Show Frame
		this.setVisible(true);
		//Set Dimension of the model to the JPanel size
		panel.delayedInit();
		
		//Update components if window was maximized
		this.addWindowStateListener(new WindowStateListener() {
			@Override
			public void windowStateChanged(WindowEvent e) {
				if ((e.getNewState() & MainFrame.MAXIMIZED_BOTH) == MainFrame.MAXIMIZED_BOTH){
					revalidate();
					panel.revalidate();
					panel.repaint();
				}
			}
		});
		
		// Panel should get Focus, so Clicks on panel would be recognized
		panel.requestFocusInWindow();
	}
}
