package lpv.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.vecmath.Vector4f;

import lpv.LPV;
import lpv.simulator.Simulator;

public class SimulatorUI extends JFrame implements Observer {
	
	public static void main(String[] args) {
		//UIManager.put("Panel.background", Color.PINK);
		
		LPVSizeDialog sizeDialog = new LPVSizeDialog();
		sizeDialog.setVisible(true);
		sizeDialog.dispose();
		
		
		if(sizeDialog.isSubmitted()) {
			int w = sizeDialog.getSubmittedWidth();
			int h = sizeDialog.getSubmittedHeight();
			int d = sizeDialog.getSubmittedDepth();
			new LPV(w, h, d);
			SimulatorUI simulator = new SimulatorUI(w, h, d);
			simulator.setVisible(true);
		}
	}
	
	private LPVVisualizer firstVisualizer;
	private LPVVisualizer secondVisualizer;
	private LPVVisualizer accumulationVisualizer;
	
	private Simulator simulator;
	private ScaleManager scale;
	private ControlPanel controlPanel;
	private StatusBar status;
	
	
	private SimulatorUI(int w, int h, int d) {
		super("LPV Simulator");
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		simulator = new Simulator(w, h, d);
		simulator.addObserver(this);
		
		setLayout(new BorderLayout());
		
		JPanel contentPanel = new JPanel();
		contentPanel.setLayout(new GridLayout(2, 2, 20, 20));
		scale = new ScaleManager(1.0f);
		contentPanel.add(firstVisualizer = new LPVVisualizer(scale, simulator.getFirst(), simulator.getGeometry()));
		contentPanel.add(secondVisualizer = new LPVVisualizer(scale, simulator.getSecond(), simulator.getGeometry()));
		contentPanel.add(accumulationVisualizer = new LPVVisualizer(scale, simulator.getAccumulation(), simulator.getGeometry()));
		contentPanel.add(controlPanel = new ControlPanel(this, simulator, scale));
		add(contentPanel, BorderLayout.CENTER);
		
		add(status = new StatusBar(), BorderLayout.SOUTH);
		
		firstVisualizer.setStatusBar(status);
		secondVisualizer.setStatusBar(status);
		accumulationVisualizer.setStatusBar(status);
		
		pack();
	}
	
	@Override
	public void update(Observable observable, Object o) {
		
		Vector4f max = new Vector4f(0.0f, 0.0f, 0.0f, 0.0f);
		
		Vector4f[] maxs = new Vector4f[] {
				simulator.getFirst().getMax(),
				simulator.getSecond().getMax(),
				simulator.getAccumulation().getMax()
		};
		
		for(Vector4f m : maxs) {
			if(m.x*m.x + m.y*m.y > max.x*max.x + max.y*max.y) {
				max.set(m);
			}
		}
		if(max.lengthSquared() > 0.01f) {
			Dimension size = accumulationVisualizer.getSHPanelSize();
			controlPanel.proposeScale((float) (Math.min(size.getWidth(), size.getHeight()) / max.length()));
		}
		
		firstVisualizer.repaint();
		secondVisualizer.repaint();
		accumulationVisualizer.repaint();
	}

}
