package com.smartgwt.sample.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.util.DateDisplayFormatter;
import com.smartgwt.client.util.DateUtil;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.FormItemValueParser;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.TextItem;

import java.util.Date;

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

    /**
     * Set system-wide default formats.
     */
    private void initDateFormats() {

        //  The format parameter may be a FormatString (http://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/docs/FormatString.html)
        DateUtil.setShortDisplayFormat("dd/MM/yy");
        DateUtil.setNormalDateDisplayFormatter(new DateDisplayFormatter() {
            @Override
            public String format(Date date) {
                if (date == null) {
                    return null;
                }
                return DateTimeFormat.getFormat("dd/MM/yy").format(date);
            }
        });

       // from the JAVADOC: "If the inputFormat is not explicitly set,the system automatically determines the standard input format will be based on the specified Date.shortDisplayFormat wherever possible"
       // DateUtil.setInputFormat("DMY");
    }


    public void onModuleLoad() {
        initDateFormats();   //seems to have no impact on DateItem

        DynamicForm form = new DynamicForm();
          form.setWidth(400);

        final DateItem dateItem = new DateItem("birthday", "Date");
        dateItem.setUseTextField(true);
        dateItem.setUseMask(true);
        dateItem.setInputFormat("DMY");

        dateItem.setEditorValueParser(new FormItemValueParser() {
            @Override
            public Object parseValue(String value, DynamicForm form, FormItem item) {
                return DateTimeFormat.getFormat("dd/MM/yy").parseStrict(value);
            }
        });

        dateItem.setEnforceDate(true);

        ButtonItem b = new ButtonItem("ok");
        b.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() {
            @Override
            public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event) {
                SC.say(dateItem.getValueAsDate().toString());
            }
        });

        form.setFields(dateItem, b);

        form.draw();

    }
}
