package com.alea.client.pages;

import java.util.Date;
import java.util.LinkedHashMap;

import com.alea.client.Messages;
import com.alea.client.data.BooleanData;
import com.alea.client.data.LoadingUnitDataSource;
import com.alea.client.services.TerminalServiceAsync;
import com.alea.client.services.TerminalService;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.rpc.HandleErrorCallback;
import com.smartgwt.client.rpc.RPCManager;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ExportDisplay;
import com.smartgwt.client.types.ExportFormat;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.util.DateDisplayFormatter;
import com.smartgwt.client.util.DateInputFormatter;
import com.smartgwt.client.util.DateUtil;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.LinkItem;
import com.smartgwt.client.widgets.form.fields.MiniDateRangeItem;
import com.smartgwt.client.widgets.form.fields.RadioGroupItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.SpacerItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.form.validator.RegExpValidator;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.DataArrivedEvent;
import com.smartgwt.client.widgets.grid.events.DataArrivedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwtpro.tools.client.SCPRO;

public class LoadingUnit {
	  
    public static void initializeLoadingUnit() {
    	
    	DateUtil.setNormalDateDisplayFormatter(new DateDisplayFormatter() {
			@Override
			public String format(Date date) {
				final DateTimeFormat dateFormatter = DateTimeFormat.getFormat("dd/MM/yyyy'<br/>'HH:mm");
				return dateFormatter.format(date);
			}
		});
		DateUtil.setShortDateDisplayFormatter(new DateDisplayFormatter() {
			@Override
			public String format(Date date) {
				final DateTimeFormat dateFormatter = DateTimeFormat.getFormat("dd/MM/yyyy");
				return dateFormatter.format(date);
			}
		});
		DateUtil.setDateInputFormatter(new DateInputFormatter () {
			@Override
			public Date parse(String dateString) {
				final DateTimeFormat dateFormatter = DateTimeFormat.getFormat("dd/MM/yyyy");
				return dateFormatter.parse(dateString);
			}
		});
		
		final BooleanData searchClicked = new BooleanData(false) ;
		
		final TerminalServiceAsync terminalService = GWT.create(TerminalService.class);
		final Messages messages = GWT.create(Messages.class);
		
		final HLayout formLayout = new HLayout(2);
		final DynamicForm formSearchLoadingUnit = new DynamicForm();
		formSearchLoadingUnit.setWidth("650px");
		final TextItem inputLoadingUnit = new TextItem();
		inputLoadingUnit.setTitle(messages.labelLoadingUnit());
		final RegExpValidator ituValidator = new RegExpValidator();
		ituValidator.setExpression("^[a-zA-Z0-9\\*]+$");
		inputLoadingUnit.setValidators(ituValidator);
		final MiniDateRangeItem departureDateItem = new MiniDateRangeItem("mdri",messages.labelDepartureDate());	
		final SelectItem departureCountryList = new SelectItem();
		departureCountryList.setName("departureCountry");
		departureCountryList.setTitle(messages.labelDepartureCountry());
		final SelectItem departureTerminalList = new SelectItem();  
		departureTerminalList.setTitle(messages.labelDepartureTerminal());
		departureTerminalList.setDisabled(true);
		departureTerminalList.setValueMap((String)null);
		departureTerminalList.setDefaultValues("");
		final SelectItem destinationCountryList = new SelectItem();
		destinationCountryList.setName("destinationCountry");
		destinationCountryList.setTitle(messages.labelDestinationCountry());
		final SelectItem destinationTerminalList = new SelectItem();  
		destinationTerminalList.setTitle(messages.labelDestinationTerminal());  
		destinationTerminalList.setDisabled(true);
		destinationTerminalList.setValueMap((String)null);
		destinationTerminalList.setDefaultValues("");
		
		terminalService.getTerminalsCountries(new AsyncCallback<LinkedHashMap<String,String>>() {
			@Override
			public void onFailure(Throwable arg0) {
				departureCountryList.setValueMap("All");
				destinationCountryList.setValueMap("All");
			}
			@Override
			public void onSuccess(LinkedHashMap<String, String> arg0) {
				departureCountryList.setValueMap(arg0);
				destinationCountryList.setValueMap(arg0);
			}
		});

		departureCountryList.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				terminalService.getTerminalsByCountry(departureCountryList.getDisplayValue(), new AsyncCallback<LinkedHashMap<String,String>>() {
					@Override
					public void onFailure(Throwable arg0) {
						departureTerminalList.setValueMap("");
						departureTerminalList.setDisabled(true);
						departureTerminalList.setDefaultValues("");
					}
					@Override
					public void onSuccess(LinkedHashMap<String, String> arg0) {
						departureTerminalList.setValueMap(arg0);
						departureTerminalList.setDefaultValues("");
						departureTerminalList.setDisabled(false);
					}
				});
			}
		});
		
		destinationCountryList.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				terminalService.getTerminalsByCountry(destinationCountryList.getDisplayValue(), new AsyncCallback<LinkedHashMap<String,String>>() {
					@Override
					public void onFailure(Throwable arg0) {
						departureTerminalList.setValueMap("");
						departureTerminalList.setDisabled(true);
						destinationTerminalList.setDefaultValues("");
					}
					@Override
					public void onSuccess(LinkedHashMap<String, String> arg0) {
						departureTerminalList.setValueMap(arg0);
						departureTerminalList.setDisabled(false);
						destinationTerminalList.setDefaultValues("");
					}
				});
			}
		});

		final RadioGroupItem showActive = new RadioGroupItem();
		showActive.setVertical(false);
		showActive.setTitle(messages.labelShowOnlyActive());
		LinkedHashMap<String, String> yesNo = new LinkedHashMap<String, String>();
		yesNo.put("1", messages.labelYes() );  
		yesNo.put("0", messages.labelNo() );
		showActive.setValueMap(yesNo);
		showActive.setDefaultValue("0");
		showActive.setColSpan(2);
		
		final IButton searchItu = new IButton( messages.buttonSearch() );
		searchItu.setStyleName("searchButton");
		searchItu.setIcon("/images/search.png");
		final IButton exportItu = new IButton( messages.xlsExport() );
		exportItu.setStyleName("exportButton");
		exportItu.setIcon("/images/iconeXls.gif");
		final IButton adminButton = new IButton("Admin Console");
		
		formSearchLoadingUnit.setNumCols(4);
		formSearchLoadingUnit.setColWidths(220,155,120,155);
		formSearchLoadingUnit.setFields(inputLoadingUnit,new SpacerItem(),departureDateItem,new SpacerItem(),departureCountryList,destinationCountryList,departureTerminalList,destinationTerminalList,showActive);

		formLayout.addMember(formSearchLoadingUnit);
		
		final VLayout buttons = new VLayout(3);
		buttons.addMember(searchItu);
		buttons.addMember(exportItu);
		buttons.addMember(adminButton);
		
		formLayout.addMember(buttons);
		
		final VLayout layout = new VLayout(0);
		// ----- ITU Code
		ListGridField ituCode = new ListGridField("ituCode",messages.labelItuCode());
		ituCode.setType(ListGridFieldType.LINK);
		ituCode.setFrozen(true);
		ituCode.setWidth(100);
		// ----- Last Status image
		ListGridField lastStatus = new ListGridField("lastStatus",messages.labelLastStatus() );
		lastStatus.setAlign(Alignment.CENTER);  
		lastStatus.setType(ListGridFieldType.IMAGE);
		lastStatus.setImageURLPrefix("../../images/status/"); // lastStatus.setImageURLPrefix("/images/status/");
		lastStatus.setImageURLSuffix(".gif");  
		lastStatus.setImageWidth(32);
		lastStatus.setImageHeight(24);
		lastStatus.setFrozen(true);
		lastStatus.setWidth(75);
		lastStatus.setCanFilter(false);
		// ----- Remarks
		ListGridField remarks = new ListGridField("remarks","Remarks");
		remarks.setFrozen(true);
		remarks.setAlign(Alignment.LEFT);
		remarks.setWidth(180);
		// ----- Custommer & Operator Reference numbers
		ListGridField refNumbers = new ListGridField("refNumbers",messages.labelReferences());
		refNumbers.setCanFilter(false);
		refNumbers.setFrozen(false);
		refNumbers.setWidth(150);
		// ----- Full / Empty
		ListGridField fullOrEmpty = new ListGridField("fullOrEmpty",messages.labelFullOrEmpty());
		fullOrEmpty.setWidth(100);
		fullOrEmpty.setCanFilter(false);
		fullOrEmpty.setFrozen(false);
		// ----- Custommers (actors)
		ListGridField actors = new ListGridField("actors",messages.labelActors());
		actors.setCanFilter(false);
		actors.setWidth(250);
		actors.setFrozen(false);
		// ----- Departure Date
		final ListGridField departureDate = new ListGridField("departureDate",messages.labelDepartureDate());
		departureDate.setCanFilter(true);
		departureDate.setType(ListGridFieldType.DATE);
		departureDate.setWidth(120);
		departureDate.setFrozen(false);
		// ----- Terminals 
		ListGridField terminals = new ListGridField("terminals",messages.labelTerminals());
		terminals.setWidth(175);
		terminals.setCanFilter(false);
		terminals.setFrozen(false);
		// ----- Control numbers
		ListGridField controlNumbers = new ListGridField("controlNumbers",messages.labelControlNumbers());
		controlNumbers.setWidth(200);
		controlNumbers.setCanFilter(false);
		// ----- HIDDEN - Departure Terminal
		final ListGridField departureTerminal = new ListGridField("departureTerminal",messages.labelDepartureTerminal());
		departureTerminal.setCanFilter(true);
		departureTerminal.setHidden(true);
		departureTerminal.setWidth(150);
		// ----- HIDDEN - Destination Terminal
		final ListGridField destinationTerminal = new ListGridField("destinationTerminal",messages.labelDestinationTerminal());
		destinationTerminal.setCanFilter(true);
		destinationTerminal.setHidden(true);
		destinationTerminal.setWidth(150);
		// ----- HIDDEN - Active transports
		ListGridField active = new ListGridField("active",messages.labelShowOnlyActiveShort());
		active.setType(ListGridFieldType.BOOLEAN);
		active.setHidden(true);
		active.setCanFilter(true);
		active.setWidth(75);
		
		final ListGrid listGrid = new ListGrid() {
			@Override  
            protected Canvas createRecordComponent(final ListGridRecord record, Integer colNum) {
				String fieldName = this.getFieldName(colNum);
				if ( "remarks".equalsIgnoreCase(fieldName) ) {
					return null ;
				} else {
					return null;
				}
			}
		};
		listGrid.setShowRecordComponents(true);
		listGrid.setShowRecordComponentsByCell(true);
		listGrid.setFields(ituCode,lastStatus,remarks,refNumbers,actors,departureDate,terminals,controlNumbers,departureTerminal,destinationTerminal,active);
		listGrid.setWidth100();
		listGrid.setHeight("530px");
		listGrid.setHeaderHeight(50);
		listGrid.setCellHeight(50);
		listGrid.setDataPageSize(50);
		listGrid.setAutoFetchData(true);
		listGrid.setShowFilterEditor(false);
		listGrid.setDataSource(LoadingUnitDataSource.getInstance());
		listGrid.addDataArrivedHandler(new DataArrivedHandler() {
			@Override
			public void onDataArrived(DataArrivedEvent event) {
				if ( event.getStartRow() != event.getEndRow() ) {
					if ( searchClicked.isValue() ) {
						toggleTabs();
						searchClicked.setValue(false);
					}
				}
			}
			native void toggleTabs() /*-{
				$wnd.toggleTabsContent();
			}-*/;
		});
		layout.addChild(listGrid);
		
		final DSCallback dsaction =  new DSCallback() {
			public void execute(DSResponse response, Object rawData, DSRequest request) {
			}
		};
		
		searchItu.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				boolean valid = formSearchLoadingUnit.validate();
				if ( valid ) {
					searchClicked.setValue(true);
					Criteria c = new Criteria();
					c.addCriteria("ituCode",(String)inputLoadingUnit.getValue());
					c.addCriteria("active",(String)showActive.getValue());
					c.addCriteria("departureFromDate",departureDateItem.getFromDate());
					c.addCriteria("departureToDate",departureDateItem.getToDate());
					c.addCriteria("departureTerminal",(String)departureTerminalList.getDisplayValue());
					c.addCriteria("destinationTerminal",(String)destinationTerminalList.getDisplayValue());
					listGrid.setFilterEditorCriteria(c);
					listGrid.invalidateCache();
					listGrid.fetchData(c,dsaction);
				}
			}
		});

		exportItu.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Window.Location.replace("../../excel/exportLoadingUnit.htm");
			}
		});
		
		adminButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				SC.showConsole();
			}
		});
		
		RPCManager.setHandleErrorCallback(new HandleErrorCallback() {
			@Override
			public void handleError(DSResponse response, DSRequest request) {
				String error = null ;
				if ( response.getHttpResponseCode() != null && response.getHttpResponseCode() == 401 ) {
					error = messages.messageError401();
				} else if ( response.getHttpResponseCode() != null && response.getHttpResponseCode() == 403 ) {
					error = messages.messageError403();	
				} else {
					error = messages.messageError(response.getHttpResponseCode().toString()) ;
				}
				if ( error != null ) {
					SC.warn(error);
				}
			}
		});

		layout.setWidth(RootPanel.get("gwtcontent").getOffsetWidth());
		Window.addResizeHandler(new ResizeHandler() {
			@Override
			public void onResize(ResizeEvent arg0) {
				layout.setWidth(RootPanel.get("gwtcontent").getOffsetWidth());
			}
		});
		
		RootPanel.get("gwtformcontent").add(formLayout);
		RootPanel.get("gwtcontent").add(layout);
    }
}
