/*
 * Isomorphic SmartGWT web presentation layer
 * Copyright 2000 and beyond Isomorphic Software, Inc.
 *
 * OWNERSHIP NOTICE
 * Isomorphic Software owns and reserves all rights not expressly granted in this source code,
 * including all intellectual property rights to the structure, sequence, and format of this code
 * and to all designs, interfaces, algorithms, schema, protocols, and inventions expressed herein.
 *
 *  If you have any questions, please email <sourcecode@isomorphic.com>.
 *
 *  This entire comment must accompany any portion of Isomorphic Software source code that is
 *  copied or moved from this file.
 */

package com.smartgwt.sample.showcase.client.dataintegration.java.form;

import java.util.Map;

import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.ValuesManager;
import com.smartgwt.client.widgets.form.events.HiddenValidationErrorsEvent;
import com.smartgwt.client.widgets.form.events.HiddenValidationErrorsHandler;
import com.smartgwt.client.widgets.form.events.SubmitValuesEvent;
import com.smartgwt.client.widgets.form.events.SubmitValuesHandler;
import com.smartgwt.client.widgets.form.fields.BooleanItem;
import com.smartgwt.client.widgets.form.fields.CanvasItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.sample.showcase.client.PanelFactory;
import com.smartgwt.sample.showcase.client.ShowcasePanel;


public class FormValidationSample extends ShowcasePanel {
    private static final String DESCRIPTION = "<p>Validation rules are automatically enforced on both the client- and server-side based on a single, shared declaration. Press \"Save\" to see errors from client-side validation.</p>" +
            "<p>Press \"Clear Errors\" then \"Disable Client Side Validation\" " +
            "then \"Save\" again to see the same errors caught by the SmartGWT EE server.</p>";

    public static class Factory implements PanelFactory {

        private String id;

        public Canvas create() {
            FormValidationSample panel = new FormValidationSample();
            id = panel.getID();
            return panel;
        }

        public String getID() {
            return id;
        }

        public String getDescription() {
            return DESCRIPTION;
        }
    }

    public Canvas getViewPanel() {
    	DataSource dataSource = DataSource.get("supplyItem");
    	final ValuesManager valuesManager = new ValuesManager(){

			@Override
			public void showErrors() {
				SC.logInfo("ValuesManager.showErrors() called");
				super.showErrors();
			}
    	};
    	valuesManager.addHiddenValidationErrorsHandler(new HiddenValidationErrorsHandler() {
			
			@Override
			public void onHiddenValidationErrors(HiddenValidationErrorsEvent event) {
				SC.logInfo("ValuesManager.onHiddenValidationErrors() called");
			}
		});
    	valuesManager.addSubmitValuesHandler(new SubmitValuesHandler() {
			
			@Override
			public void onSubmitValues(SubmitValuesEvent event) {
				SC.logInfo("ValuesManager.onSubmitValues() called");
			}
		});
    	valuesManager.setDataSource(dataSource);
    	
    	
        final DynamicForm form = new DynamicForm();
        //form.setUseAllDataSourceFields(false);
        form.setDataSource(dataSource);
        form.setFields(
        		new TextItem("itemID"),
        		//new TextItem("itemName"),
        		//new TextItem("SKU"),
        		new TextItem("description"),
        		new TextItem("category"),
        		new SelectItem("units"),
        		//new FormItem("unitCost"),
        		new BooleanItem("inStock"),
        		new DateItem("nextShipment")
        		);
        valuesManager.addMember(form);
        
        
        final String itemName = "itemName";
        final String compositeFieldName = "compositeFieldName";
        final CanvasItem compositeItem = new CanvasItem(compositeFieldName, "Item Name / SKU");
        //compositeItem.setShowErrorIcon(true);
        
        final DynamicForm form2 = new DynamicForm();
        //form2.setUseAllDataSourceFields(false);
        form2.setDataSource(dataSource);
        form2.setFields(
        		compositeItem,
        		new FormItem("unitCost")
        		);
        valuesManager.addMember(form2);
        
        
        final DynamicForm form3 = new DynamicForm(){
			//@Override
			public void showErrors() {
				SC.logInfo("NestedForm.showErrors() called");
				Map errors = getErrors();
				if(errors.containsKey(itemName)){
					Object fieldErrors = errors.get(itemName);
					SC.logInfo("NestedForm.showErrors() for itemName: " + fieldErrors);
					if(fieldErrors instanceof String){
						form2.setFieldErrors(compositeFieldName, getField(itemName).getTitle() + ":" + (String)fieldErrors, true);
					}else if(fieldErrors instanceof String[]){
						form2.setFieldErrors(compositeFieldName, getField(itemName).getTitle() + ":" + (String[])fieldErrors, true);
					}else{
						SC.logInfo("NestedForm.showErrors() - cannot set the errors for itemName: " + fieldErrors);
					}
					errors.remove(itemName);
					setErrors(errors, true);
				}else{
					super.showErrors();
				}
			}
        };
        form3.setDataSource(dataSource);
        //form3.setUseAllDataSourceFields(false);
        form3.setFields(
        		new TextItem(itemName),
        		new TextItem("SKU"));
        form3.setNumCols(4);
        compositeItem.setCanvas(form3);
        valuesManager.addMember(form3);
        
        //prefill some values
        valuesManager.setValue("unitCost", -1.234);
        valuesManager.setValue("SKU", "mySKU");

        IButton saveButton = new IButton("Save");
        saveButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
            	valuesManager.saveData();
            }
        });

        IButton clearErrorsButton = new IButton("Clear Errors");
        clearErrorsButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
            	valuesManager.clearErrors(true);
            }
        });

        final IButton disableValidationButton = new IButton("Disable Client Side Validation");
        disableValidationButton.setAutoFit(true);
        disableValidationButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Boolean validation = valuesManager.getDisableValidation();
                validation = validation == null ? false : validation;
                valuesManager.setDisableValidation(!validation);
                disableValidationButton.setTitle((valuesManager.getDisableValidation() ? "Enable" : "Disable") + " Client Side Validation");
            }
        });

        HStack buttons = new HStack(10);
        buttons.setHeight(24);
        buttons.setMembers(saveButton, clearErrorsButton, disableValidationButton);

        VLayout layout = new VLayout(10);
        layout.setMembers(form,form2, buttons);
        return layout;
    }

    public String getIntro() {
        return DESCRIPTION;
    }

}