package es.dalocar.facturamas.swt.edit;

import java.util.EventListener;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import es.dalocar.facturamas.swt.SWTUtils;
import es.dalocar.facturamas.swt.components.SaveCancelComposite;
import es.dalocar.software.ApplicationManager;
import es.dalocar.software.Context;
import es.dalocar.software.Messages;
import es.dalocar.software.beans.LineaFactura;
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.
 */
public class EditLineaFacturaComposite extends
		org.eclipse.swt.widgets.Composite {

	private static Logger log = Logger
			.getLogger(EditLineaFacturaComposite.class.getName());
	private static boolean DEBUG = log.isDebugEnabled();
	private static boolean INFO = log.isInfoEnabled();

	private EditDetailLineaFactura editDetailLineaFactura1;
	private SaveCancelComposite saveCancelComposite1;

	private ApplicationManager manager;
	private boolean editMode;
	private String initialState;


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

	/**
	 * Overriding checkSubclass allows this class to extend
	 * org.eclipse.swt.widgets.Composite
	 */
	protected void checkSubclass() {
	}

	/**
	 * Auto-generated method to display this org.eclipse.swt.widgets.Composite
	 * inside a new Shell.
	 */
	public static void showGUI() {
		Display display = Display.getDefault();
		Shell shell = new Shell(display);
		
		EditLineaFacturaComposite inst = new EditLineaFacturaComposite(shell,
				SWT.CLOSE);
		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);
		}
		
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	public EditLineaFacturaComposite(org.eclipse.swt.widgets.Composite parent,
			int style) {
		super(parent, style);
		initGUI();
	}

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public EditLineaFacturaComposite(org.eclipse.swt.widgets.Composite parent,
			int style, boolean editMode) {
		super(parent, style);
		initGUI();

		manager = ApplicationManager.getManager();
		this.editMode = editMode;

		refresh();

		bindModifyListeners();
		bindButtonListeners();

		initialState = SWTUtils.calculateState(this);

	}

	/**
	 * Metodo que abre deja el nuevo composite en el bucle de espera de eventos
	 */
	public void open() {
		final Display display = Display.getCurrent();
		Shell shell = this.getShell();
		shell .addListener(SWT.CLOSE, new Listener() {			
			public void handleEvent(Event arg0) {
				manejar();				
			}
		});
		Point size = this.getSize();
		shell.setLayout(new FillLayout());
		shell.layout();
		if (size.x == 0 && size.y == 0) {
			this.pack();
			shell.pack();
		} else {
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}
		SWTUtils.openCentered(shell, false);
	}

	private void initGUI() {

		this.addListener(SWT.Close, new Listener() {
		      public void handleEvent(Event event) {
		        manejar();
		      }
		});
		try {
			RowLayout thisLayout = new RowLayout(org.eclipse.swt.SWT.VERTICAL);
			thisLayout.type = SWT.VERTICAL;
			thisLayout.wrap = false;
			this.setLayout(thisLayout);
			{
				editDetailLineaFactura1 = new EditDetailLineaFactura(this,
						SWT.NONE);
				editDetailLineaFactura1.getTxtNumLinea().setEditable(false);
				GridLayout editDetailLineaFactura1Layout = new GridLayout();
				editDetailLineaFactura1Layout.numColumns = 2;
				editDetailLineaFactura1
						.setLayout(editDetailLineaFactura1Layout);
			}
			{

				saveCancelComposite1 = new SaveCancelComposite(this, SWT.NONE);
				GridLayout saveCancelComposite1Layout = new GridLayout(2, true);
				saveCancelComposite1.setLayout(saveCancelComposite1Layout);
			}
			this.setTabList(new org.eclipse.swt.widgets.Control[] {editDetailLineaFactura1, saveCancelComposite1});
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void refresh() {
		LineaFactura linea = getLineaFacturaContext();
		if (DEBUG)
			log.debug(">>REFRESH" + linea);
		
		if (editMode) {
			this.editDetailLineaFactura1.getTxtDescripcion().setText(
					linea.getDescripcion());
			this.editDetailLineaFactura1.getTxtIVA().setText(
					linea.getIva().toString());
		
			this.editDetailLineaFactura1.getTxtPrecio().setText(
					linea.getPrecio().toString());
			this.editDetailLineaFactura1.getTxtCantidad().setText(
					linea.getCantidad().toString());
		} else {
			this.editDetailLineaFactura1.getTxtDescripcion().setText(ResourceUtils.getString(ResourceUtils.DESC_LINEAFACTURA));
			this.editDetailLineaFactura1.getTxtIVA().setText(ResourceUtils.getString(ResourceUtils.IVA_LINEAFACTURA));
			this.editDetailLineaFactura1.getTxtPrecio().setText(ResourceUtils.getString(ResourceUtils.PRECIO_LINEAFACTURA));
			this.editDetailLineaFactura1.getTxtCantidad().setText(ResourceUtils.getString(ResourceUtils.CANT_LINEAFACTURA));
		}
		this.editDetailLineaFactura1.getTxtNumLinea().setText(linea.getId().getNumerolinea().toString());
	}

	/**
	 * Añade los listeners de modificación a los campos del formulario
	 */
	private void bindModifyListeners() {

		// Descripción
		this.editDetailLineaFactura1.getTxtDescripcion().addModifyListener(
				new ModifyListener() {
					public void modifyText(ModifyEvent evt) {
						if (DEBUG) {
							log.debug("dpFecha.modifyText, event=" + evt);
						}
						checkModify();

					}
				});

		// Cantidad
		this.editDetailLineaFactura1.getTxtCantidad().addModifyListener(
				new ModifyListener() {
					public void modifyText(ModifyEvent evt) {
						if (DEBUG) {
							log.debug("dpFecha.modifyText, event=" + evt);
						}
						checkModify();

					}
				});

		// IVA
		this.editDetailLineaFactura1.getTxtIVA().addModifyListener(
				new ModifyListener() {
					public void modifyText(ModifyEvent evt) {
						if (DEBUG) {
							log.debug("dpFecha.modifyText, event=" + evt);
						}
						checkModify();

					}
				});

		// Precio
		this.editDetailLineaFactura1.getTxtPrecio().addModifyListener(
				new ModifyListener() {
					public void modifyText(ModifyEvent evt) {
						if (DEBUG) {
							log.debug("dpFecha.modifyText, event=" + evt);
						}
						checkModify();

					}
				});

	}

	/**
	 * Añade los listeners a los botones del formulario
	 */
	private void bindButtonListeners() {

		final Button botonGuardar = this.saveCancelComposite1.getBtnGuardar();
		botonGuardar.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {

				if (log.isDebugEnabled()) {
					log.debug("buttonModif.widgetSelected, event=" + evt);
				}

				if (checkModify()) {
					MessageBox m = new MessageBox(getShell(), SWT.YES | SWT.NO 	| SWT.CANCEL | SWT.ICON_QUESTION);
					m.setMessage(Messages.getString("EditPeticionComposite.save.changes"));
					int valor = m.open();
					if (valor == SWT.YES) {
						populate();
						// if (validate()) {
						// save();
						if(validate())
							getShell().dispose();
					}
					if (valor == SWT.NO) {
						// Salir directamente
						getShell().dispose();
						if(!editMode) {
							if(DEBUG)
								log.debug("NO seleccionado -> Modo edicion: " + editMode );
							Context ctx = ApplicationManager.getManager().getContext();
							ctx.setAttribute(LineaFactura.class.getName(),null);
						}
					}
				} else {
					getShell().dispose();
				}
			}

		

		});
		
					
		final Button botonCancelar = this.saveCancelComposite1.getBtnCancelar();
		botonCancelar.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				manejar();
			}
		});
		
		
	}

	/**
	 * Comprobar el estado del formulario
	 * 
	 * @return Devuelve true si se ha producido alguna modificación en el
	 *         formulario, false en caso contrario
	 * 
	 */
	private boolean checkModify() {
		String currentState = SWTUtils.calculateState(this);

		if (DEBUG) {
			log.debug("initialState: " + initialState);
			log.debug("currentState: " + currentState);
		}

		boolean modified = !initialState.equals(currentState);
		this.saveCancelComposite1.getBtnGuardar().setEnabled(modified);
		return modified;
	}

	/**
	 * Metodo que valida los campos del formulario.
	 * 
	 * @return True si la validación es correcta, false en caso contrario
	 */
	private boolean validate() {

		List result = null;

		// Validaciones del formulario
		LineaFactura lineaFactura = getLineaFacturaContext();

		result = manager.validate(lineaFactura);

				
		// Mostrar mensaje si procede
		if (!result.isEmpty()) {
			SWTUtils.showValidatonErrors(getShell(), manager.constructValidationString(result));
		}

		return result.isEmpty();
	}
	
	/**
	 * 
	 */
	private void populate() {
		
		LineaFactura linea = getLineaFacturaContext();
		linea.setDescripcion(this.editDetailLineaFactura1.getTxtDescripcion().getText());
		linea.setCantidad(new Double(this.editDetailLineaFactura1.getTxtCantidad().getText()));
		linea.setIva(new Double(this.editDetailLineaFactura1.getTxtIVA().getText()));
		linea.setPrecio(new Double(this.editDetailLineaFactura1.getTxtPrecio().getText()));
	}
	
	/**
	 * Obtiene la Linea Factura guardada en contexto
	 * @return
	 */
	private LineaFactura getLineaFacturaContext() {
		Context ctx = ApplicationManager.getManager().getContext();
		return (LineaFactura) ctx.getAttribute(LineaFactura.class.getName());
	}

	private void manejar() {
		
		if (checkModify()) {
			MessageBox m = new MessageBox(getShell(), SWT.YES | SWT.NO 	| SWT.ICON_QUESTION);
			m.setMessage(Messages.getString("EditPeticionComposite.save.changes"));
			int valor = m.open();
			if (valor == SWT.YES) {
				getShell().dispose();
			} else {
				if(!editMode) {
					if(DEBUG)
						log.debug("NO seleccionado -> Modo edicion: " + editMode );
					Context ctx = ApplicationManager.getManager().getContext();
					ctx.setAttribute(LineaFactura.class.getName(),null);
				}
			}
		}
		else  {
			getShell().dispose();
			if(!editMode) {
				if(DEBUG)
					log.debug("NO seleccionado -> Modo edicion: " + editMode );
				Context ctx = ApplicationManager.getManager().getContext();
				ctx.setAttribute(LineaFactura.class.getName(),null);
			}
		}
	}
}
