package customformitem.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.core.KeyIdentifier;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.EnterKeyEditAction;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.KeyCallback;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class CustomFormItem implements EntryPoint {

    HLayout body = new HLayout();
    ListGrid g = new ListGrid();
    
    DataSource ds = CountryDS.getInstance();
    
    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {
        KeyIdentifier debugKey = new KeyIdentifier();
        debugKey.setCtrlKey(true);
        debugKey.setKeyName("E");

        Page.registerKey(debugKey, new KeyCallback() {
            public void execute(String keyName) {
                SC.showConsole();
            }
        });

        GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler(){
            @Override
            public void onUncaughtException(Throwable e) {
                Date date = new Date();
                DateTimeFormat sdf = DateTimeFormat.getFormat("MM/dd/yyyy HH:mm:ss");
                System.err.println(sdf.format(date)+" Uncaught Exception intercepted ");
                e.printStackTrace();
            }
        });
        

        DeferredCommand.addCommand( 
                        new Command() {
                           public void execute() {
                               init();
                               RootPanel.get().add(body);
                           }
                        } );
    }
    
    public void init() {

        g.setDataSource(ds);
        g.setCanEdit(true);
        g.setEnterKeyEditAction(EnterKeyEditAction.DONE);
        g.setModalEditing(true);
        g.setAutoSaveEdits(true);
        g.setSelectionType(SelectionStyle.SINGLE);
        g.setHeight(500);

        body.addMember(g);

        body.setWidth("100%");
        body.setBackgroundColor("lightgrey");
        g.show();
        g.fetchData();

    }

    private static class CountryDS extends DataSource {
        // The DataSource would normally be defined external to any classes that use it.

        private static CountryDS instance = null;
        
        public static CountryDS getInstance() {
            if (instance == null) {
              instance = new CountryDS("countryDS_XML");
            }
            return instance;
        }

        public CountryDS(String id) {
            setID(id);

            this.setClientOnly(true);
            DataSourceField field1 = new DataSourceTextField("id", "ID");
            DataSourceField field2 = new DataSourceTextField("customField", "Custom");
            
            TheFormItem customFormItem = new TheFormItem("customField");
            field2.setEditorType(customFormItem);
            
            setFields(field1, field2);
            
        }
        
        protected java.lang.Object transformRequest(DSRequest dsRequest) {

            if (dsRequest.getOperationType() == DSOperationType.FETCH) {
                fetch(dsRequest);
            } else if (dsRequest.getOperationType() == DSOperationType.ADD) {
                addRow(dsRequest);
            } else if (dsRequest.getOperationType() == DSOperationType.UPDATE) {
                updateRow(dsRequest);
            } else if (dsRequest.getOperationType() == DSOperationType.REMOVE) {
                deleteRow(dsRequest);
            }

            // no need to return payload to caller
            return "transformReturnString";
        }

        private void fetch(DSRequest dsRequest) {
            List<ListGridRecord> records = new ArrayList<ListGridRecord>();

            ListGridRecord r = new ListGridRecord();
            r.setAttribute("id", "1");
            r.setAttribute("customField","custom1");
            records.add(r);
            
            r = new ListGridRecord();
            r.setAttribute("id", "2");
            r.setAttribute("customField","custom2");
            records.add(r);
            
            DSResponse response = new DSResponse();
            response.setStatus(DSResponse.STATUS_SUCCESS);
            response.setData(records.toArray(new ListGridRecord[0]));
            this.processResponse(dsRequest.getRequestId(), response);
        }
        
        // we receive a single row/record which is to be added to the database
        private void addRow(DSRequest dsRequest) {
        }
        private void updateRow(DSRequest dsRequest) {
        }
        private void deleteRow(DSRequest dsRequest) {
        }

        class TheFormItem extends TextItem {


            public TheFormItem() {
                super();
                init();
            }

            public TheFormItem(JavaScriptObject jso) {
                super(jso);
                init();
            }

            public TheFormItem(String name) {
                super(name);
                init();
            }

            public TheFormItem(String name, String title) {
                super(name, title);
                init();
            }

            private void init() {
                setAttribute("editorType", "customformitem.client.TheFormItem");
            }
        }

    }


}
