package hibergui.property;

import hibergui.Form;
import hibergui.I18n;
import hibergui.Util;
import hibergui.verify.DateFormatConstraint;
import hibergui.verify.SelfConstraint;
import hibergui.verify.VerificationError;

import java.text.ParseException;
import java.util.Date;

import org.eclipse.swt.widgets.Composite;

public class DateEdit extends TextEdit<Date> {

    public static DefaultComputation<Date> today = new DefaultComputation<Date>() {
		public Date defaultValue() {
			return new Date();
		}
    };

    public DateEdit(Form form, Composite cptParent, int style, String prop, String name) {
		super(form, cptParent, style, prop, name);

		addConstraint(
                new SelfConstraint() {
					public boolean check() {
						String s = getText();
						if (s == null)
							return true;
						return DateFormatConstraint.parseDate(s);
					}
                },
                new VerificationError(
                		I18n.get("constraint.dateformat.0") +
                		getName() +
                		I18n.get("constraint.dateformat.2")
                		)
        );
	}

	@Override
	public void fill() {
		setText(Util.ensureString(get()));
	}

	@Override
	public Date extract() {
		try {
			return Util.dateFormat.parse(getText());
		} catch (ParseException e) {
			return null;
		} catch (NullPointerException e) {
			return null;
		}
	}
}
