package com.smartgwt.sample.showcase.client.mvc;

import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.ResultSet;
import com.smartgwt.client.data.events.DataChangedEvent;
import com.smartgwt.client.data.events.DataChangedHandler;
import com.smartgwt.client.types.Alignment;
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.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.viewer.DetailViewer;
import com.smartgwt.sample.showcase.client.PanelFactory;
import com.smartgwt.sample.showcase.client.ShowcasePanel;
import com.smartgwt.sample.showcase.client.data.CountryXmlDS;
import com.smartgwt.sample.showcase.client.data.ItemSupplyXmlDS;

public class PatternReuseSample extends ShowcasePanel {
    private static final String DESCRIPTION = "<p>This example illustrates DataSource driven widgets. The Grid and Form widgets themselves are completely driven by the DataSource definition and do not have any code " +
            "specific to displaying labels or fields from either datasource.</p>" +
            "<p>Click to select a DataSource, click on records to edit them in the adjacent form, then click the \"Save\" button to save changes. This resuable component combines a databound form and grid into " +
            "a reusable application pattern of side-by-side editing, that can be used with any DataSource.</p>";

    private static String LOG_CATEGORY = "PatternReuseSample";
    
    public static class Factory implements PanelFactory {
        private String id;

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

        public String getID() {
            return id;
        }

        public String getDescription() {
            return DESCRIPTION;
        }
    }

    @Override
    protected boolean isTopIntro() {
        return true;
    }

    public Canvas getViewPanel() {
        final DataSource countryDS = CountryXmlDS.getInstance();
        final DataSource supplyItemDS = ItemSupplyXmlDS.getInstance();

        final CompoundEditor cEditor = new CompoundEditor(countryDS);

        SelectItem dsSelect = new SelectItem();
        dsSelect.setName("datasource");
        dsSelect.setShowTitle(false);
        dsSelect.setValueMap("country", "supply");
        dsSelect.addChangedHandler(new ChangedHandler() {
            public void onChanged(ChangedEvent event) {
                String ds = (String) event.getValue();
                if (ds.equalsIgnoreCase("country")) {
                    cEditor.setDatasource(countryDS);
                } else {
                    cEditor.setDatasource(supplyItemDS);
                }
            }
        });
        DynamicForm form = new DynamicForm();
        form.setValue("datasource", "Select a DataSource");
        form.setItems(dsSelect);

        VLayout layout = new VLayout(15);
        layout.setWidth100();
        layout.setHeight("80%");

        layout.addMember(form);
        layout.addMember(cEditor);


        return layout;
    }


    private static class CompoundEditor extends HLayout {
        private DataSource datasource;
        private DynamicForm form;
        private ListGrid grid;
        private IButton saveButton;
		private DetailViewer detailViewer;
		private DynamicForm formReadOnly;

        private CompoundEditor(DataSource datasource) {
            this.datasource = datasource;
        }

        @Override 
        protected void onInit() {
            super.onInit();
            this.form = new DynamicForm();

            form.setDataSource(datasource);

            saveButton = new IButton("Save");
            saveButton.setLayoutAlign(Alignment.CENTER);
            saveButton.addClickHandler(new ClickHandler() {

                public void onClick(ClickEvent event) {
                    form.saveData(new DSCallback() {
						
						@Override
						public void execute(final DSResponse response, Object rawData, DSRequest request) {
							SC.logDebug("form.saveData.callback() called", LOG_CATEGORY);
							//TODO: how to achieve auto refresh of detailViewer and formReadOnly without these lines
							//detailViewer.setData(response.getData());
							//formReadOnly.editRecord(response.getData()[0]);
						}
					});
                }
            });

            VLayout editorLayout = new VLayout(5);
            editorLayout.addMember(form);
            editorLayout.addMember(saveButton);
            editorLayout.setWidth(280);

            grid = new ListGrid();
            grid.setWidth(500);
            grid.setHeight(350);
            grid.setDataSource(datasource);
            grid.setAutoFetchData(true);
            grid.addRecordClickHandler(new RecordClickHandler() {
            	private ResultSet detailViewerResultSet;
                private ResultSet formReadOnlyResultSet;

				public void onRecordClick(RecordClickEvent event) {
                    form.clearErrors(true);
                    form.editRecord(event.getRecord());
                    saveButton.enable();

                    // detailViewer version 1 - provides auto refresh
                    if(detailViewerResultSet != null){
                    	detailViewerResultSet.destroy(); //if not destroyed the old object still observes the datasource operations
                    }
                    detailViewerResultSet = new ResultSet(datasource);
                    detailViewerResultSet.destroy();
                    detailViewerResultSet.setID(SC.generateID("ResultSet_detailViewer"));
                    detailViewerResultSet.setAllRows(new Record[]{event.getRecord()});                    
                    detailViewer.setData(detailViewerResultSet);
                    
                    // detailViewer version 2 - provides auto refresh
                    //String pk = event.getRecord().getAttribute("pk");
                    //detailViewer.fetchData(new Criteria("pk", pk));
                    
                    // detailViewer version 3 - doesn't provide auto refresh
                    //detailViewer.setData(new Record[]{event.getRecord()});
                    
                    formReadOnly.editRecord(event.getRecord());
                    //formReadOnly.fetchData(new Criteria("pk", pk)); //doesn't provide aut refresh
                    
/*                  //  formReadOnly - provides auto refresh; encapsulated in AutoRefreshDynamicForm
					if(formReadOnlyResultSet != null){
                    	formReadOnlyResultSet.destroy(); //if not destroyed the old object still observes the datasource operations
                    }
                    formReadOnlyResultSet = new ResultSet();
                    formReadOnlyResultSet.setDataSource(datasource);
                    formReadOnlyResultSet.setID(SC.generateID("ResultSet_formReadOnly"));
                    formReadOnlyResultSet.setAllRows(new Record[]{event.getRecord()});
                    formReadOnlyResultSet.addDataChangedHandler(new DataChangedHandler() {
						
						@Override
						public void onDataChanged(DataChangedEvent event) {
							SC.logWarn("formReadOnlyResultSet - onDataChanged() called");
							if(formReadOnlyResultSet.isEmpty()){
								formReadOnly.clearValues();
							}else{
								formReadOnly.editRecord(formReadOnlyResultSet.get(0));
							}
						}
					});
                    formReadOnlyResultSet.ensureCreated();*/
                }

            });

            detailViewer = new DetailViewer();
            detailViewer.setDataSource(datasource);           
            
            
            //formReadOnly = new DynamicForm();
            formReadOnly = new AutoRefreshDynamicForm();
            formReadOnly.setCanEdit(false);
            formReadOnly.setDataSource(datasource);
            
            addMember(grid);
            addMember(editorLayout);
            addMember(detailViewer);
            addMember(formReadOnly);
            
        }

        public DataSource getDatasource() {
            return datasource;
        }

        public void setDatasource(DataSource datasource) {
            this.datasource = datasource;
            grid.setDataSource(datasource);
            form.setDataSource(datasource);
            detailViewer.setDataSource(datasource);
            formReadOnly.setDataSource(datasource);
            saveButton.disable();
            grid.fetchData();
        }
    }
    
    static private class AutoRefreshDynamicForm extends DynamicForm{
    	private static String LOG_CATEGORY = "AutoRefreshDynamicForm";

    	private ResultSet resultSet;
		
		@Override
		public void editRecord(Record record) {
			SC.logDebug("editRecord("+(record==null ? "null" : record.toMap())+") called", LOG_CATEGORY);
			if(resultSet != null){
            	resultSet.destroy(); //if not destroyed the old object still observes the datasource operations
            }
			if(record != null){
	            resultSet = new ResultSet();
	            resultSet.setDataSource(getDataSource());
	            resultSet.setID(SC.generateID("ResultSet_form"));
	            resultSet.setAllRows(new Record[]{record});
	            resultSet.addDataChangedHandler(new DataChangedHandler() {
					
					@Override
					public void onDataChanged(DataChangedEvent event) {
						SC.logDebug("resultSet - onDataChanged() called", LOG_CATEGORY);
						if(resultSet==null || resultSet.isEmpty()){
							clearValues();
						}else{
							editRecord(resultSet.get(0));
						}
					}
				});
	            resultSet.ensureCreated();
			}
			
			super.editRecord(record);
		}
    }

    @Override
    public String getIntro() {
        return DESCRIPTION;
    }
}