package es.dalocar.facturamas.swt;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import es.dalocar.facturamas.swt.handlers.ClienteListHandler;
import es.dalocar.facturamas.swt.handlers.ListaFacturasHandler;
import es.dalocar.software.ApplicationManager;
import es.dalocar.software.Messages;
import es.dalocar.software.utils.ResourceUtils;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
/**
 * Composite principal de la aplicación
 */
public class MainComposite extends org.eclipse.swt.widgets.Composite {

	/** Config file name path, relative to user.dir */
	private static final String LOG4J_CONFIG_FILENAME = "conf/log4j.properties"; //$NON-NLS-1$

	/** The log4j logger */
	private static final Logger log = Logger.getLogger(MainComposite.class
			.getName());
	private MenuItem listadosMenuItem;
	private Menu listadosMenu;
	private static final boolean DEBUG = log.isDebugEnabled();
	private static final boolean INFO = log.isInfoEnabled();

	private Menu menu1;
	private MenuItem listadoAlumnosMenuItem;
	private MenuItem exitMenuItem;

	private Label titleLabel;
	private Label imgLabel;
	private Label label1;
	private MenuItem menuItemClientes;

	private  static ApplicationManager manager;

	{
		// Register as a resource user - SWTResourceManager will
		// handle the obtaining and disposing of resources
		SWTResourceManager.registerResourceUser(this);
	}

	/**
	 * Constructor que inicializa la GUI y obtiene una referencia al
	 * ApplicationManager
	 * 
	 * @param parent
	 * @param style
	 */
	public MainComposite(Composite parent, int style) {
		super(parent, style);
		initGUI();

		// $hide>>$
		manager = ApplicationManager.getManager();
		// $hide<<$

		getShell().setText("Menú Principal");
		createAccelerators();
		addListeners();
	}

	/**
	 * Initializes the GUI.
	 */
	private void initGUI() {
		try {
			FormLayout thisLayout = new FormLayout();
			this.setLayout(thisLayout);
			// START >> imgLabel
			imgLabel = new Label(this, SWT.NONE);
			imgLabel.setImage(SWTResourceManager
					.getImage("es/dalocar/facturamas/res/favicon.ico")); //$NON-NLS-1$

			FormData imgLabelLData = new FormData();
			imgLabelLData.width = 560;
			imgLabelLData.height = 294;
			imgLabelLData.left = new FormAttachment(0, 1000, 0);
			imgLabelLData.right = new FormAttachment(1000, 1000, 0);
			imgLabelLData.bottom = new FormAttachment(773, 1000, 0);
			imgLabel.setLayoutData(imgLabelLData);
			imgLabel.setAlignment(SWT.CENTER);
			// END << imgLabel
			// START >> titleLabel
			titleLabel = new Label(this, SWT.NONE);
			titleLabel
					.setText(Messages.getString("MainComposite.company.name")); //$NON-NLS-1$
			titleLabel.setFont(SWTResourceManager.getFont(
					"Tahoma", 11, 1, false, false)); //$NON-NLS-1$
			titleLabel.setAlignment(SWT.CENTER);
			FormData titleLabelLData = new FormData();
			titleLabelLData.width = 399;
			titleLabelLData.height = 21;
			titleLabelLData.top = new FormAttachment(807, 1000, 0);
			titleLabelLData.left = new FormAttachment(1, 1000, 0);
			titleLabelLData.right = new FormAttachment(1000, 1000, -1);
			titleLabelLData.bottom = new FormAttachment(871, 1000, 0);
			titleLabel.setLayoutData(titleLabelLData);
			// END << titleLabel
			// START >> label1
			label1 = new Label(this, SWT.NONE);
			label1.setAlignment(SWT.CENTER);
			label1.setText(Messages.getString("MainComposite.app.title")); //$NON-NLS-1$
			FormData label1LData = new FormData();
			label1LData.width = 399;
			label1LData.height = 21;
			label1LData.left = new FormAttachment(1, 1000, 0);
			label1LData.right = new FormAttachment(1000, 1000, -1);
			label1LData.top = new FormAttachment(871, 1000, 0);
			label1LData.bottom = new FormAttachment(934, 1000, 0);
			label1.setLayoutData(label1LData);
			label1.setFont(SWTResourceManager.getFont(
					"Tahoma", 11, 1, false, false)); //$NON-NLS-1$
			// END << label1

			// $hide>>$
			// Establecer la imagen desde recursos
			String imgPath = ResourceUtils.getString(ResourceUtils.IMAGE_LOGO);
			imgLabel.setImage(SWTResourceManager.getImage(imgPath));
			// $hide<<$

			this.setSize(560, 419);
			this.setEnabled(false);
			{
				menu1 = new Menu(getShell(), SWT.BAR);
				getShell().setMenuBar(menu1);
				{
					listadosMenuItem = new MenuItem(menu1, SWT.CASCADE);
					listadosMenuItem.setText("&Listados");
					{
						listadosMenu = new Menu(listadosMenuItem);
						listadosMenuItem.setMenu(listadosMenu);
						{
							listadoAlumnosMenuItem = new MenuItem(listadosMenu, SWT.PUSH);
							listadoAlumnosMenuItem.setText("&Facturas");
						}
						{
							menuItemClientes = new MenuItem(listadosMenu, SWT.PUSH);
							menuItemClientes.setText("Clientes");
						}
					}
				}
				{
					exitMenuItem = new MenuItem(menu1, SWT.PUSH);
					exitMenuItem.setText("&Salir");
				}
			}
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Auto-generated main method to display this
	 * org.eclipse.swt.widgets.Composite inside a new Shell.
	 */
	public static void main(String[] args) {

		// $hide>>$
		configureLog4j();

		if (INFO) {
			log.info("Inicio de la aplicacion"); //$NON-NLS-1$
			log.info("Platform: " + SWT.getPlatform()); //$NON-NLS-1$
			log.info("SWT version: " + SWT.getVersion()); //$NON-NLS-1$
		}
		// $hide<<$

		Display display = Display.getDefault();
		Shell shell = new Shell(display);
		MainComposite inst = new MainComposite(shell, SWT.NULL);
		Point size = inst.getSize();
		shell.setLayout(new FillLayout());
		shell.layout();
		if (size.x == 0 && size.y == 0) {
			inst.pack();
			shell.pack();
		} else {
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}

		// $hide>>$
		// Establecer el icono de la aplicación desde recursos
		String iconPath = ResourceUtils.getString(ResourceUtils.IMAGE_APP_ICON);
		shell.setImage(SWTResourceManager.getImage(iconPath));

		// Maximizar la ventana principal
		shell.setMaximized(true);
		// $hide<<$

		// Abrir la ventana principal
		shell.open();

		while (!shell.isDisposed()) {
			// $protect>>$
			try {
				if (!display.readAndDispatch())
					display.sleep();
			} catch (Exception e) {
				handleError(shell, e);
			}
			// $protect<<$
		}

		// $hide>>$
		if (INFO)
			log.info("Fin de la aplicacion"); //$NON-NLS-1$
		// $hide<<$

	}

	/**
	 * Manejador general de errores. La implementacion muestra una pantalla de
	 * error con un mensaje genérico.
	 * 
	 * @param shell
	 *            Active Shell
	 * @param e
	 *            Exception
	 */
	private static void handleError(Shell shell, Exception e) {

		log.fatal("Unexpected!: " + e.getMessage(), e); //$NON-NLS-1$

		if (ResourceUtils.getBoolean(ResourceUtils.DEVELOP_MODE)) {
			shell.dispose();
			throw new RuntimeException(e);
		} else {
			MessageBox m = new MessageBox(shell, SWT.ICON_ERROR);
			m.setText(Messages.getString("MainComposite.general.error.title")); //$NON-NLS-1$
			m
					.setMessage(Messages
							.getString("MainComposite.general.error") + ": " + e.getMessage()); //$NON-NLS-1$
			m.open();
		}
	}

	/**
	 * Configure the log4j system from disk, and watch it
	 * 
	 */
	private static void configureLog4j() {
		PropertyConfigurator.configureAndWatch(LOG4J_CONFIG_FILENAME);
	}

	/**
	 * Listeners de la aplicación
	 * 
	 */
	private void addListeners() {

		// Listado de alumnos
		listadoAlumnosMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				if (DEBUG) {
					log.debug("listadoAlumnosMenuItem.widgetSelected, event=" //$NON-NLS-1$
							+ evt);
				}
				new ListaFacturasHandler().run(MainComposite.this);
			}
		});
		
		
		// Listado de alumnos
		menuItemClientes.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				if (DEBUG) {
					log.debug("listadoAlumnosMenuItem.widgetSelected, event=" //$NON-NLS-1$
							+ evt);
				}
				new ClienteListHandler().run(MainComposite.this);
			}
		});

		// Salir
		exitMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {

				if (DEBUG) {
					log.debug("exitMenuItem.widgetSelected, event=" + evt); //$NON-NLS-1$
				}

				Display display = Display.getDefault();
				MessageBox messageBox = new MessageBox(
						display.getActiveShell(), SWT.YES | SWT.NO
								| SWT.ICON_QUESTION);
				messageBox.setText(Messages
						.getString("MainComposite.exit.title")); //$NON-NLS-1$
				messageBox.setMessage(Messages
						.getString("MainComposite.exit.question")); //$NON-NLS-1$
				int valor = messageBox.open();
				if (valor == SWT.YES) {
					display.getActiveShell().dispose();
				}
			}
		});

	}

	/**
	 * Crea los aceleradores de teclado
	 * 
	 */
	private void createAccelerators() {

		listadoAlumnosMenuItem.setAccelerator(SWT.CONTROL | SWT.SHIFT | 'A');

	}

}