package com.hraccess.ta.projects.ou.client.view.widget.grids;

import static com.hraccess.ta.projects.gwt.client.utils.FieldsName.HOUR_NATURE_LABEL;
import static com.hraccess.ta.projects.gwt.client.utils.FieldsName.OU_LABEL;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.core.client.GWT;
import com.hraccess.ta.projects.gwt.client.service.OrganizationalUnitService;
import com.hraccess.ta.projects.gwt.client.service.OrganizationalUnitServiceAsync;
import com.hraccess.ta.projects.gwt.client.utils.DateFormattersClient;
import com.hraccess.ta.projects.gwt.client.utils.FieldsName;
import com.hraccess.ta.projects.gwt.client.utils.TAMessages;
import com.hraccess.ta.projects.gwt.client.utils.UserPreferencesConstants;
import com.hraccess.ta.projects.gwt.shared.serializable.ConfigurationMetaData;
import com.hraccess.ta.projects.ou.client.datasource.AddressDatasource;
import com.hraccess.ta.projects.ou.client.datasource.CodePaysDS;
import com.hraccess.ta.projects.ou.client.datasource.CodePostalDatasource;
import com.hraccess.ta.projects.ou.client.datasource.INSEEDatasource;
import com.hraccess.ta.projects.ou.client.datasource.LieuDitDS;
import com.hraccess.ta.projects.ou.client.datasource.SearchDatasource;
import com.hraccess.ta.projects.ou.client.record.TaskRecord;
import com.hraccess.ta.projects.ou.client.view.widget.menus.ListGridMenu;
import com.hraccess.ta.projects.planning.canvas.shared.serializable.DaySZ;
import com.hraccess.ta.projects.planning.canvas.shared.util.Util;
import com.hraccess.ta.projects.planning.client.view.individual.body.HourNatureCalculatedListGrid;
import com.hraccess.ta.projects.planning.common.datasource.OrganizationalUnitDS;
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.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.Autofit;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SortDirection;
import com.smartgwt.client.util.Offline;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.EditorExitEvent;
import com.smartgwt.client.widgets.form.fields.events.EditorExitHandler;
import com.smartgwt.client.widgets.form.validator.CustomValidator;
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.ChangeEvent;
import com.smartgwt.client.widgets.grid.events.ChangeHandler;
import com.smartgwt.client.widgets.grid.events.ChangedEvent;
import com.smartgwt.client.widgets.grid.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.events.EditCompleteEvent;
import com.smartgwt.client.widgets.grid.events.EditCompleteHandler;
import com.smartgwt.client.widgets.grid.events.EditFailedEvent;
import com.smartgwt.client.widgets.grid.events.EditFailedHandler;
import com.smartgwt.client.widgets.menu.events.ClickHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;


public class AddressListGrid extends ListGrid{

	public ListGridMenu contextMenu = new ListGridMenu(FieldsName.ADDRESS, new ListGridMenu.ITEM_MENU[] {ListGridMenu.ITEM_MENU.CREATE});
	
	public static OrganizationalUnitServiceAsync uoService = GWT.create(OrganizationalUnitService.class);
	public static ComboBoxItem codePostalCombo = new ComboBoxItem(FieldsName.CODE_POST);
	public ComboBoxItem communeCombo = new ComboBoxItem(FieldsName.Commune);
	public ComboBoxItem inseeCombo = new ComboBoxItem(FieldsName.Insee);
	public ComboBoxItem codePaysCombo = new ComboBoxItem();
	public ComboBoxItem LieuditCombo= new ComboBoxItem(FieldsName.OU_LIEUDIT);
	public ListGridField code_postal = new ListGridField(FieldsName.OU_CODE_POST, TAMessages.getMessage("ta.ou.address.postal.code"));
	public ListGridField commune = new ListGridField(FieldsName.OU_COMMUNE, TAMessages.getMessage("ta.ou.address.commune"));
	public  ListGridField insee = new ListGridField(FieldsName.OU_INSEE, TAMessages.getMessage("ta.ou.address.insee"));
	public ListGridField Lieudit = new ListGridField(FieldsName.OU_LIEUDIT,"Lieu-dit");

	
	public AddressListGrid() {
		 createListGrid();
		 initHandlers();
	}
	
	public void createListGrid(){
		
		setEmptyMessage(TAMessages.getMessage("ta.noItemToShow"));
	    setShowHeader(true);  
 	    setCanEdit(true);  
 		setCanReorderRecords(false);  
 		setShowCellContextMenus(false);
 		setShowHeaderContextMenu(true);
 		setFixedRecordHeights(true);
 		setRecordComponentHeight(20);
 		setAlternateRecordStyles(false);
 		setCanSort(true);
 		setHeaderHeight(30);
 		setHeaderSpanHeight(15);
 		setShowHover(false);
 		setCanHover(false);
 		setShowRollOver(false);
 		setShowAllRecords(true);
 		
 		SelectItem BisTerSelectItem = new SelectItem();
		setEmptyMessage(TAMessages.getMessage("ta.noItemToShow"));
		TextItem textItemMask = new TextItem();
		setCanRemoveRecords(true);
		
		DateItem dateMask = new DateItem();
		dateMask.setUseMask(true);
		dateMask.setEndDate(new Date (new Date().getYear() + 10,1,1)); 
		setWidth100();
		setHeight("65%");
		setCanEdit(true);
		setAlign(Alignment.CENTER);
		setCellHeight(20);
		setAutoFitData(Autofit.VERTICAL);
		setAlign(Alignment.CENTER);
		
		codePostalCombo.setTooltip(TAMessages.getMessage("ta.warn.PostalCode"));
		communeCombo.setTooltip(TAMessages.getMessage("ta.warn.Commmune1"));
		inseeCombo.setTooltip(TAMessages.getMessage("ta.warn.INSEE"));	
		LieuditCombo.setTooltip(TAMessages.getMessage("ta.warn.LieuDit"));

		ListGridField startDateField = new ListGridField(FieldsName.ADDRESS_START_DATE, TAMessages.getMessage("ta.date.start"));
	    startDateField.setType(ListGridFieldType.DATE);
	    startDateField.setWidth("10%");
	    startDateField.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
	    startDateField.setRequired(true);
	    startDateField.setAlign(Alignment.LEFT);
	    startDateField.setSortDirection(SortDirection.DESCENDING);
	    startDateField.setCanGroupBy(false);
	    startDateField.setCanHide(false);
	    startDateField.setEditorProperties(dateMask);
        final CustomValidator dateValidator = new CustomValidator() {
            @Override
            protected boolean condition(Object date) {

                   String  value =DateFormattersClient.dateFormatterforService.format((Date)date);
                   boolean result = false;
                   if (value == null || !value.toString().contains("/")) {
                   result = true;
                   } else if (value.toString().length() == 0){
                          result = true;
                   }
                   else {
                          String[] tab = value.toString().split("/");
                          try{
                                String year =tab[2];
                                if (year.length()< 4 || year.charAt(0)=='0') {
                                result = false;
                          } else {
                                result = true;
                          }
                          }
                                catch(Exception e){
                                       return false;
                                }
                   }
                   return result;
            }
     };
     startDateField.setValidators(dateValidator);

	    final ListGridField pays = new ListGridField(FieldsName.Pays, TAMessages.getMessage("ta.ou.pays"));
		pays.setWidth("7%");

		pays.setRequired(true);
		pays.setDefaultValue("FRA");
		
		this.codePaysCombo.setValidateOnChange(true);
		codePaysCombo.setOptionDataSource(CodePaysDS.getInstance());
		codePaysCombo.setEmptyPickListMessage(TAMessages.getMessage("ta.noItemToShow"));
		
		pays.setEditorProperties(codePaysCombo);
		
		ListGridField streetNum = new ListGridField(FieldsName.OU_STREET_NUM, TAMessages.getMessage("ta.ou.address.street.number"));
		streetNum.setWidth("3%");
		streetNum.setType(ListGridFieldType.INTEGER);
		streetNum.setAlign(Alignment.LEFT);
		textItemMask.setLength(4);
		streetNum.setEditorProperties(textItemMask);

		ListGridField bis_ter = new ListGridField(FieldsName.OU_BIS_TER, TAMessages.getMessage("ta.ou.address.bis"));
		bis_ter.setWidth("7%");
		LinkedHashMap<String, String> bisTerValueMap = new LinkedHashMap<String, String>();  
		bisTerValueMap.put("", "");
		bisTerValueMap.put("T", "Ter");
		bisTerValueMap.put("B", "Bis");
		BisTerSelectItem.setValueMap (bisTerValueMap);
		bis_ter.setEditorProperties(BisTerSelectItem);
		bis_ter.setValueMap(bisTerValueMap);

		ListGridField streetName = new ListGridField(FieldsName.OU_STREET_NAME, TAMessages.getMessage("ta.ou.address.street.name"));
		streetName.setWidth("8%");
		textItemMask.setLength(32);
		streetName.setEditorProperties(textItemMask);

		ListGridField completeAddress = new ListGridField(FieldsName.OU_COMPLADDRESS, TAMessages.getMessage("ta.ou.address.complement"));
		completeAddress.setWidth("15%");
		textItemMask.setLength(38);
		completeAddress.setEditorProperties(textItemMask);
		
		this.code_postal.setWidth("8%");
		this.code_postal.setCanFilter(true);
		this.code_postal.setRequired(true);
		this.code_postal.setEditorProperties(createComboBoxItemForCodePostal(codePostalCombo));
		
		commune.setWidth("12%");
		commune.setCanFilter(true);
		commune.setRequired(false);
		commune.setEditorProperties(createComboBoxItemForCommune(communeCombo));		
		
		insee.setWidth("8%");
		insee.setCanFilter(true);
		insee.setRequired(false);
		insee.setEditorProperties(createComboBoxItemForINSEE(inseeCombo));
		
		Lieudit.setWidth("13%");
		this.LieuditCombo.setValidateOnChange(true);
		LieuditCombo.setEmptyPickListMessage(TAMessages.getMessage("ta.noItemToShow"));
		Lieudit.setEditorProperties(createComboBoxItemForLieuDit(LieuditCombo));
		
		
		
		setFields(startDateField, pays, streetNum, bis_ter, streetName,
				completeAddress, code_postal, commune, Lieudit ,insee);

		setContextMenu(contextMenu);

		contextMenu.getItem(0).addClickHandler(new ClickHandler() {
			@Override
			public void onClick(MenuItemClickEvent event) {
				TaskRecord record = new TaskRecord();
				startEditingNew(record);
			}
		});
	}

	private ComboBoxItem createComboBoxItemForCodePostal(ComboBoxItem comb) {
	    setTitle(TAMessages.getMessage("ta.project"));
		comb.setOptionDataSource(CodePostalDatasource.getInstance());
		comb.setAllowEmptyValue(false);
		comb.setValidateOnChange(true);
		comb.setMinimumSearchLength(2);
		comb.setSearchStringTooShortMessage(TAMessages.getMessage("ta.warn.PostalCode"));
		comb.setDisplayField(FieldsName.OU_CODE_POST);
		comb.setValueField(FieldsName.OU_CODE_POST);
		comb.setPickListWidth(100);
		comb.setEmptyPickListMessage(TAMessages.getMessage("ta.noItemToShow"));
		comb.setFilterFields(FieldsName.OU_CODE_POST);
		comb.setUseClientFiltering(true);
		ListGridField codeField = new ListGridField(FieldsName.OU_CODE_POST);
		comb.setSortField(FieldsName.OU_CODE_POST);
		codeField.setCanFilter(true);
		codeField.setWidth(100);
		ListGrid pickListProperties = new ListGrid();
		pickListProperties.setEmptyMessage(TAMessages.getMessage("ta.noItemToShow"));	
		pickListProperties.setFilterButtonPrompt(TAMessages.getMessage("ta.action.filter"));
		comb.setPickListProperties(pickListProperties);
		setAutoFetchData(true);
		comb.setPickListFields(codeField);
		return comb;
	}
	
	private ComboBoxItem createComboBoxItemForCommune(final ComboBoxItem comb) {
		setTitle(TAMessages.getMessage("ta.project"));
		comb.setOptionDataSource(AddressDatasource.getInstance(this));
		comb.setAllowEmptyValue(false);
		comb.setValidateOnChange(true);
        //comb.setMinimumSearchLength(2);
		//comb.setSearchStringTooShortMessage(TAMessages.getMessage("ta.warn.commune1"));
		comb.setValidateOnChange(true);
		comb.setDisplayField(FieldsName.OU_COMMUNE);
		comb.setValueField(FieldsName.OU_COMMUNE);
		comb.setPickListWidth(400);
		comb.setEmptyPickListMessage(TAMessages.getMessage("ta.noItemToShow"));
		comb.setFilterFields(FieldsName.OU_COMMUNE);
		comb.setUseClientFiltering(true);
		ListGridField pkField = new ListGridField(FieldsName.PK);
		ListGridField codeField = new ListGridField(FieldsName.OU_CODE_POST);
		ListGridField communeField = new ListGridField(FieldsName.OU_COMMUNE);
		ListGridField LieuDitField = new ListGridField(FieldsName.OU_LIEUDIT);
		ListGridField inseeField = new ListGridField(FieldsName.OU_INSEE);
        comb.setSortField(FieldsName.PK);
		codeField.setCanFilter(true);
		codeField.setWidth(100);
		ListGrid pickListProperties = new ListGrid();
		pickListProperties.setEmptyMessage(TAMessages.getMessage("ta.noItemToShow"));
//		pickListProperties.setFilterButtonPrompt(TAMessages.getMessage("ta.action.filter"));
		setAutoFetchData(true);
		comb.setPickListFields(pkField,codeField,communeField,LieuDitField,inseeField);
		comb.setPickListProperties(pickListProperties);
		return comb;
	}
	
	private ComboBoxItem createComboBoxItemForINSEE(ComboBoxItem comb) {
		setTitle(TAMessages.getMessage("ta.project"));
		comb.setOptionDataSource(INSEEDatasource.getInstance(this));
		comb.setAllowEmptyValue(false);
		comb.setMinimumSearchLength(2);
		//comb.setSearchStringTooShortMessage(TAMessages.getMessage("ta.warn.INSEE"));
		comb.setDisplayField(FieldsName.OU_INSEE);
		comb.setValueField(FieldsName.OU_INSEE);
		comb.setPickListWidth(400);
		comb.setValidateOnChange(true);
		comb.setEmptyPickListMessage(TAMessages.getMessage("ta.noItemToShow"));
		comb.setFilterFields(FieldsName.OU_INSEE);
		comb.setUseClientFiltering(true);
		comb.setLength(5);
		ListGridField codeField = new ListGridField(FieldsName.OU_CODE_POST);
		ListGridField communeField = new ListGridField(FieldsName.OU_COMMUNE);
		ListGridField LieuDitField = new ListGridField(FieldsName.OU_LIEUDIT);
		ListGridField inseeField = new ListGridField(FieldsName.OU_INSEE);
        comb.setSortField(FieldsName.OU_INSEE);
		codeField.setCanFilter(true);
		codeField.setWidth(100);
		ListGrid pickListProperties = new ListGrid();
		pickListProperties.setEmptyMessage(TAMessages.getMessage("ta.noItemToShow"));	
		pickListProperties.setFilterButtonPrompt(TAMessages.getMessage("ta.action.filter"));
		comb.setPickListProperties(pickListProperties);
		setAutoFetchData(true);
		comb.setPickListFields(codeField,communeField,LieuDitField,inseeField);
		return comb;
	}

	private ComboBoxItem createComboBoxItemForLieuDit(ComboBoxItem comb) {
		setTitle(TAMessages.getMessage("ta.project"));
		comb.setOptionDataSource(LieuDitDS.getInstance(this));
		comb.setAllowEmptyValue(false);
		comb.setDisplayField(FieldsName.OU_LIEUDIT);
		comb.setValueField(FieldsName.OU_LIEUDIT);
		comb.setPickListWidth(400);
		comb.setEmptyPickListMessage(TAMessages.getMessage("ta.noItemToShow"));
		comb.setUseClientFiltering(true);
		comb.setValidateOnChange(true);
		ListGridField codeField = new ListGridField(FieldsName.OU_CODE_POST);
		ListGridField communeField = new ListGridField(FieldsName.OU_COMMUNE);
		ListGridField LieuDit = new ListGridField(FieldsName.OU_LIEUDIT);
		ListGridField inseeField = new ListGridField(FieldsName.OU_INSEE);
		
        comb.setSortField(FieldsName.OU_LIEUDIT);
		codeField.setCanFilter(true);
		codeField.setWidth(100);
		ListGrid pickListProperties = new ListGrid();
		pickListProperties.setEmptyMessage(TAMessages.getMessage("ta.noItemToShow"));	
		pickListProperties.setFilterButtonPrompt(TAMessages.getMessage("ta.action.filter"));
		comb.setPickListProperties(pickListProperties);
		setAutoFetchData(true);
		comb.setPickListFields(codeField,communeField,LieuDit,inseeField);
		return comb;
	}
	
	private void initHandlers() {
		code_postal.addChangeHandler(new
				com.smartgwt.client.widgets.grid.events.ChangeHandler() {
				 @Override
				 public void onChange(
				 com.smartgwt.client.widgets.grid.events.ChangeEvent event) {
					 
					 int maxLength = 15;
					 
				 String codePays =(String) getEditedCell(event.getRowNum(), "pays");
				
				 if ("FRA".equals(codePays) || "MAR".equals(codePays) || "ITA".equals(codePays) || "ESP".equals(codePays)) {
					 maxLength = 5;
				 }
				 else if ("BEL".equals(codePays)) {
					 maxLength = 4;
				 }
				 else if ("NLD".equals(codePays) || "CAN".equals(codePays)) {
					 maxLength = 6;
				 }
				
				 else if ("PRT".equals(codePays)) {
					 maxLength = 7;
				 }
				
				 else if ("GBR".equals(codePays)) {
					 maxLength = 8;
				 }
				
				 else if ("DEU".equals(codePays) || "CHE".equals(codePays) || "USA".equals(codePays)) {
					 maxLength = 9;
				 }
					 if(event.getValue().toString()!=null)
						 if(event.getValue().toString().length() > maxLength)
							 event.cancel();
				 }
			 });
	
		
	this.code_postal.addChangedHandler(new ChangedHandler(){
			@Override
			public void onChanged(final ChangedEvent event) {
				
				if( event.getValue()!=null)
				{
					event.getForm().getField(FieldsName.OU_INSEE).clearValue();
					event.getForm().getField(FieldsName.OU_LIEUDIT).clearValue();
					event.getForm().getField(FieldsName.OU_COMMUNE).clearValue();

					String codePostal = event.getValue().toString();
					Date tmp = new Date();

			    final Criteria postalCriteria = new Criteria(FieldsName.OU_CODE_POST, codePostal);
			    postalCriteria.addCriteria("tdp", tmp);
				commune.setOptionCriteria(postalCriteria);
				Lieudit.setOptionCriteria(postalCriteria);
				insee.setOptionCriteria(postalCriteria);

				AddressDatasource.getInstance().fetchData(postalCriteria, new DSCallback() {
					@Override
					public void execute(DSResponse response, Object rawData, DSRequest request) {
						 Record[] records = response.getData();

					        if (records != null && records.length >1)
					        {
								event.getForm().getField(FieldsName.OU_COMMUNE).setOptionCriteria(postalCriteria);
								event.getForm().getField(FieldsName.OU_LIEUDIT).setOptionCriteria(postalCriteria);
								event.getForm().getField(FieldsName.OU_INSEE).setOptionCriteria(postalCriteria);
                              
					        }
					        if (records != null && records.length ==1)
					        {
				                     Record record = records[0];
				                    event.getForm().getField(FieldsName.OU_COMMUNE).setValue(record.getAttribute(FieldsName.OU_COMMUNE));
				        			event.getForm().getField(FieldsName.OU_COMMUNE).focusInItem();
				        			event.getForm().getField(FieldsName.OU_LIEUDIT).setValue(record.getAttribute(FieldsName.OU_LIEUDIT));
				        			event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
				        			event.getForm().getField(FieldsName.OU_INSEE).setValue(record.getAttribute(FieldsName.OU_INSEE));
				        			event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
									}
								}
							});
				}
			}
		});
		
					
		this.Lieudit.addChangedHandler(new ChangedHandler(){
			@Override
			public void onChanged(final ChangedEvent event) {
				 if(event.getValue()!=null && event.getForm().getField(FieldsName.OU_CODE_POST).getValue()!=null
						 && event.getValue()!=null && event.getForm().getField(FieldsName.OU_COMMUNE).getValue()!=null
						 && event.getValue().toString()!=null) {
					    event.getForm().getField(FieldsName.OU_INSEE).clearValue();
			            Date da = new Date();
			            
			            String codeLieuDit =  event.getValue().toString();
			            String codeCommune = event.getForm().getField(FieldsName.OU_COMMUNE).getValue().toString();
						String codePostal = event.getForm().getField(FieldsName.OU_CODE_POST).getValue().toString();
					    
                        final Criteria lieuDitCriteria= new Criteria(FieldsName.OU_LIEUDIT,codeLieuDit);
						
                        lieuDitCriteria.addCriteria(FieldsName.OU_CODE_POST,codePostal);
                        lieuDitCriteria.addCriteria(FieldsName.OU_COMMUNE,codeCommune);
                        lieuDitCriteria.addCriteria("tDp", da);		
						
						Lieudit.setOptionCriteria(lieuDitCriteria);
						insee.setOptionCriteria(lieuDitCriteria);
				 
						SearchDatasource.getInstance().fetchData(lieuDitCriteria, new DSCallback() {
							@Override
							public void execute(DSResponse response, Object rawData, DSRequest request) {
								
								 Record[] records = response.getData();
								  if (records != null && records.length ==1)
							         {
						                Record record = records[0];
		                            	event.getForm().getField(FieldsName.OU_INSEE).setValue(record.getAttribute(FieldsName.OU_INSEE));
			                            event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
											}
							}
						});
				 }
			}
		});

		
		commune.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				if(event.getValue()==null){
					event.getForm().getField(FieldsName.OU_INSEE).clearValue();
					event.getForm().getField(FieldsName.OU_LIEUDIT).clearValue();    
					 
					event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
                    event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
                    event.getForm().getField(FieldsName.OU_COMMUNE).focusInItem();
				}				
			}
		});
		
		
		Lieudit.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				if(event.getValue()==null){
					//event.getForm().getField(FieldsName.OU_COMMUNE).clearValue();
					//event.getForm().getField(FieldsName.OU_INSEE).clearValue();    
                    event.getForm().getField(FieldsName.OU_COMMUNE).focusInItem();
                    event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
					event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
				}				
			}
		});
		
		code_postal.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				if(event.getValue()==null){
					event.getForm().getField(FieldsName.OU_COMMUNE).clearValue();
					event.getForm().getField(FieldsName.OU_INSEE).clearValue();
					event.getForm().getField(FieldsName.OU_LIEUDIT).clearValue();
 
                    event.getForm().getField(FieldsName.OU_COMMUNE).focusInItem();
                    event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
				    event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
	                event.getForm().getField(FieldsName.OU_CODE_POST).focusInItem();

				}					
			}
		});

		insee.addChangeHandler(new ChangeHandler() {
	                          		                                                   
			@Override
			public void onChange(ChangeEvent event) {
			
				if(event.getValue()==null){
					 event.getForm().getField(FieldsName.OU_COMMUNE).clearValue();
					 event.getForm().getField(FieldsName.OU_LIEUDIT).clearValue();    
					
					 event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
                     event.getForm().getField(FieldsName.OU_COMMUNE).focusInItem();
                     event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
				
				}
			}
		});
		
		this.insee.addChangedHandler(new
				com.smartgwt.client.widgets.grid.events.ChangedHandler() {
				
				 @Override
				 public void onChanged(
				 final com.smartgwt.client.widgets.grid.events.ChangedEvent event) {
					 if(event.getValue()!=null && event.getForm().getField(FieldsName.OU_CODE_POST).getValue()!=null)
					 {						 
						Date da = new Date();
						event.getForm().getField(FieldsName.OU_COMMUNE).clearValue();
						event.getForm().getField(FieldsName.OU_LIEUDIT).clearValue();                    
						
						if(event.getForm().getField(FieldsName.OU_INSEE).getValue().toString().length()==0){
							 event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
		                     event.getForm().getField(FieldsName.OU_COMMUNE).focusInItem();
		                     event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
						
						}
			 
						String codeInsee = event.getValue().toString();
						String codePostal = event.getForm().getField(FieldsName.OU_CODE_POST).getValue().toString();

						final Criteria communeCriteria= new Criteria(FieldsName.OU_INSEE,codeInsee);
						
						communeCriteria.addCriteria(FieldsName.OU_CODE_POST,codePostal);
						communeCriteria.addCriteria(FieldsName.OU_INSEE,codeInsee);
						communeCriteria.addCriteria("tDp", da);		
						
						commune.setOptionCriteria(communeCriteria);
						insee.setOptionCriteria(communeCriteria);
						Lieudit.setOptionCriteria(communeCriteria);
						SearchDatasource.getInstance().fetchData(communeCriteria, new DSCallback() {
							@Override
							public void execute(DSResponse response, Object rawData, DSRequest request) {
								 Record[] records = response.getData();
								    if (records != null && records.length >1)
							        {
								    
									event.getForm().getField(FieldsName.OU_LIEUDIT).setOptionCriteria(communeCriteria);
									event.getForm().getField(FieldsName.OU_COMMUNE).setOptionCriteria(communeCriteria);
							        }

							        if (records != null && records.length ==1)
							        {
						                Record record = records[0];			
						                event.getForm().getField(FieldsName.OU_LIEUDIT).setValue(record.getAttribute(FieldsName.OU_LIEUDIT));
					        			event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
		                               	event.getForm().getField(FieldsName.OU_COMMUNE).setValue(record.getAttribute(FieldsName.OU_COMMUNE));
		                                event.getForm().getField(FieldsName.OU_COMMUNE).focusInItem();
									}
							 }
						   });
						}
					}
				});
		
		this.commune.addChangedHandler(new
				com.smartgwt.client.widgets.grid.events.ChangedHandler() {
				
				 @Override
				 public void onChanged(
				 final com.smartgwt.client.widgets.grid.events.ChangedEvent event) {
					 if(event.getValue()!=null && event.getForm().getField(FieldsName.OU_CODE_POST).getValue()!=null)
					 {
						Date da = new Date();
						 
						event.getForm().getField(FieldsName.OU_LIEUDIT).clearValue();			 
						String codeCommune = event.getValue().toString();
						String codePostal  = event.getForm().getField(FieldsName.OU_CODE_POST).getValue().toString();

						final Criteria communeCriteria= new Criteria(FieldsName.OU_COMMUNE,codeCommune);
						
						communeCriteria.addCriteria(FieldsName.OU_CODE_POST,codePostal);
						communeCriteria.addCriteria("tDp", da);		
						
						commune.setOptionCriteria(communeCriteria);
						insee.setOptionCriteria(communeCriteria);
						Lieudit.setOptionCriteria(communeCriteria);
						SearchDatasource.getInstance().fetchData(communeCriteria, new DSCallback() {
							@Override
							public void execute(DSResponse response, Object rawData, DSRequest request) {
								 Record[] records = response.getData();
								 LinkedHashMap <Integer ,String> communeMap =new LinkedHashMap <Integer ,String>();
								 LinkedHashMap <Integer ,String> lieuMap =new LinkedHashMap <Integer ,String>();
								 int pk =0;

								    if (records != null && records.length >1)
							        {	
									event.getForm().getField(FieldsName.OU_LIEUDIT).setOptionCriteria(communeCriteria);
						SC.warn("tot"+event.getForm().getField(FieldsName.OU_COMMUNE).getSelectedRecord().getAttribute(FieldsName.OU_LIEUDIT));
									for (Record rec:records){
										lieuMap.put(rec.getAttributeAsInt(FieldsName.PK), rec.getAttribute(FieldsName.OU_LIEUDIT));
										communeMap.put(rec.getAttributeAsInt(FieldsName.PK), rec.getAttribute(FieldsName.OU_COMMUNE));
									}
									for(Entry <Integer,String> entry:communeMap.entrySet()){
										if(event.getValue().toString().equals(entry.getValue())){
								       pk=entry.getKey();
								       break;
										}
									}
										for(Entry <Integer,String> entry:lieuMap.entrySet()){
											if(pk==entry.getKey()){
				                                event.getForm().getField(FieldsName.OU_LIEUDIT).setValue(entry.getValue());
							        			event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();	
							        			break;
											}	
										
									}
//									  
//						                event.getForm().getField(FieldsName.OU_LIEUDIT).setValue(record.getAttribute(FieldsName.OU_LIEUDIT));
//					        			event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
//										for(Record rec:records){
//											if(rec.getAttribute(FieldsName.PK).equalsIgnoreCase(event.getForm().getField(FieldsName.OU_COMMUNE).getSelectedRecord().getAttribute(FieldsName.PK))){
//				                                event.getForm().getField(FieldsName.OU_LIEUDIT).setValue(rec.getAttribute(FieldsName.OU_LIEUDIT));
//							        			event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
//				                                break;
//
//											}
//										}
							        }

							        if (records != null && records.length ==1)
							        {
						                Record record = records[0];
						                event.getForm().getField(FieldsName.OU_LIEUDIT).setValue(record.getAttribute(FieldsName.OU_LIEUDIT));
					        			event.getForm().getField(FieldsName.OU_LIEUDIT).focusInItem();
		                               	event.getForm().getField(FieldsName.OU_INSEE).setValue(record.getAttribute(FieldsName.OU_INSEE));
		                                event.getForm().getField(FieldsName.OU_INSEE).focusInItem();
		                                
											}
										}
									});

						}
					}
				});
//		this.addEditorExitHandler(new com.smartgwt.client.widgets.grid.events.EditorExitHandler() {
//
//			@Override
//			public void onEditorExit(
//					com.smartgwt.client.widgets.grid.events.EditorExitEvent event) {
//				if (event.getGrid().hasErrors()) {
//					ConfigurationMetaData.INSTANCE().setIsFalseAddress(true);
//				}
//			}
//		});

//    this.addEditorExitHandler(new com.smartgwt.client.widgets.grid.events.EditorExitHandler() {
//
//			@Override
//			public void onEditorExit(
//					com.smartgwt.client.widgets.grid.events.EditorExitEvent event) {
//				int validRows = 0,invalidRows=0;
//				
//				for (Record rec : event.getGrid().getRecords()) {
//
//					if (event.getGrid().v) {
//						validRows++;
//					} else {
//						invalidRows++;
//					}
//				}
//				if(invalidRows!=0){
//                    ConfigurationMetaData.INSTANCE().setIsFalseAddress(true);
//					
//				}
//			}
//
//		});

	}

	/**
	 * Save user's preferences
	 */
	public void savePreferences() {
        String viewState = getViewState();
        Offline.put(UserPreferencesConstants.OU_PROJECTSECTION_ADRESSE_VIEWSTATE, viewState);
        SC.say(TAMessages.getMessage("ta.action.preferences.saved"));
	}
}