/*
 *  Name:    $Id: MainApp.java,v 1.14 2010/02/05 13:28:24 t724w Exp $
 * 
 *  Copyright 2009 Bundesamt für Informatik und Telekommunikation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ch.admin.bit.edec.evv.ui.swing;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

import ch.admin.bit.edec.dsig.Environment;

/**
 * 
 * Main Window
 * 
 * @author mru
 * 
 */
public class MainApp extends JFrame implements FileInputChangedListener {

	private int width = 580;
	private int height = 520;

	private String evv = "";
	private String ca = "";
	private String crl = "";

	private boolean saveConfig = false;

	private String iconPath = "/icon.png";

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public MainApp() {
		setLayout(new BorderLayout());
		loadConfig();

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		setTitle("eVV Validator GUI " + Environment.getVersion());

		// set iocn

		Image icon = Environment.getImage(iconPath);

		if (icon != null) {
			setIconImage(icon);
		}

		// add menu
		setJMenuBar(createMenu(this));

		OperationPanel opPanel = new OperationPanel(this);

		List<FileInputChangedListener> listeners = new ArrayList<FileInputChangedListener>();
		listeners.add(this);
		listeners.add(opPanel);

		JPanel north = new JPanel(new GridLayout(0, 1));

		north.add(new FileInputPanel(FileInputType.EVV, evv, listeners));
		north.add(new FileInputPanel(FileInputType.CRL, crl, listeners));
		north.add(new FileInputPanel(FileInputType.CA, ca, listeners));

		add(north, BorderLayout.NORTH);
		add(opPanel, BorderLayout.CENTER);
		setSize(width, height);

		addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				height = e.getWindow().getHeight();
				width = e.getWindow().getWidth();

				saveConfig();
			}

		});

	}

	private void loadConfig() {

		Properties properties = Environment.loadConfig();

		String configCA = properties.getProperty(Environment.CA);

		if (configCA != null) {
			this.ca = configCA;
		}

		String configCRL = properties.getProperty(Environment.CRL);

		if (configCRL != null) {
			this.crl = configCRL;
		}

		String configEVV = properties.getProperty(Environment.EVV);

		if (configEVV != null) {
			this.evv = configEVV;
		}

		String configWidth = properties.getProperty(Environment.WINDOW_WIDTH);

		if (configWidth != null) {
			try {
				this.width = Integer.valueOf(configWidth);
			} catch (NumberFormatException e) {
				// do nothing use default value

			}
		}

		String configHeight = properties.getProperty(Environment.WINDOW_HEIGHT);

		if (configHeight != null) {
			try {
				this.height = Integer.valueOf(configHeight);
			} catch (NumberFormatException e) {
				// do nothing use default value

			}
		}

		String configLAF = properties.getProperty(Environment.LAF);

		// set look and feel
		if (configLAF != null) {
			try {
				UIManager.setLookAndFeel(configLAF);
			} catch (Exception e) {
				// try to set native look and feel
				try {
					UIManager.setLookAndFeel(UIManager
							.getSystemLookAndFeelClassName());
				} catch (Exception ex) {
					// do nothing use default --> CrossPlatformLookAndFeel
					// (Metal)
					ex.printStackTrace();
				}
			}

		} else {
			// set look and feel to native
			try {
				UIManager.setLookAndFeel(UIManager
						.getSystemLookAndFeelClassName());
			} catch (Exception e) {
				// do nothing use default --> CrossPlatformLookAndFeel
				// (Metal)
				e.printStackTrace();
			}
		}

	}

	private void saveConfig() {

		if (saveConfig == false) {
			// skip do not save current config
			return;
		}

		Properties properties = new Properties();

		properties.setProperty(Environment.CA, ca);
		properties.setProperty(Environment.CRL, crl);
		properties.setProperty(Environment.EVV, evv);

		properties.setProperty(Environment.WINDOW_HEIGHT, String
				.valueOf(height));

		properties.setProperty(Environment.WINDOW_WIDTH, String.valueOf(width));

		properties.setProperty(Environment.LAF, UIManager.getLookAndFeel()
				.getClass().getName());

		Environment.saveConfig(properties);

	}

	public void onFilePathChanged(String path, FileInputType source) {
		switch (source) {
		case CA:
			ca = path;
			break;

		case CRL:
			crl = path;
			break;

		case EVV:
			evv = path;
			break;

		default:
			break;
		}

	}

	public void setSaveConfig(boolean saveConfig) {
		this.saveConfig = saveConfig;
	}

	public JMenuBar createMenu(final JFrame parent) {

		JMenuBar bar = new JMenuBar();

		JMenu infoMenu = new JMenu("Info");
		JMenuItem about = new JMenuItem("About eVV Validator");
		infoMenu.add(about);

		about.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				Image image = Environment.getImage(iconPath);

				String title = "e-dec eVV Validator "
						+ Environment.getVersion();
				String text = "You will find more information about e-dec on the swiss customs homepage (http://www.ezv.admin.ch)";
				text += Environment.getLicense();

				if (image != null) {
					Icon icon = new ImageIcon(image);

					JOptionPane.showMessageDialog(parent, text, title,
							JOptionPane.INFORMATION_MESSAGE, icon);

				} else {
					JOptionPane.showMessageDialog(parent, text, title,
							JOptionPane.INFORMATION_MESSAGE);
				}

			}
		});

		JMenu lafMenu = new JMenu("Look'n'Feel");

		LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();

		for (final LookAndFeelInfo lafInfo : lafs) {
			String text = lafInfo.getName();
			JMenuItem item = new JMenuItem(text);
			lafMenu.add(item);
			item.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {

					try {
						UIManager.setLookAndFeel(lafInfo.getClassName());
						saveConfig();
						SwingUtilities.updateComponentTreeUI(getRootFrame());

						getRootFrame().pack();

					} catch (Exception ex) {
						// error do nothing
						System.err.println(ex);
					}
				}
			});
		}

		bar.add(infoMenu);
		bar.add(lafMenu);

		return bar;
	}

	private JFrame getRootFrame() {
		return this;
	}

}
