package cc.smtweb.framework.core.mvc.controller.binder.param;

import cc.smtweb.framework.core.exception.BindParamException;
import org.apache.commons.lang3.StringUtils;

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

public class DateEditor extends AbstractParameterEditor {
    public DateEditor(int header) {
        super(header);
    }

    @Override
    protected Object parseText(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Date) {
            return new java.sql.Date(((Date) value).getTime());
        }

        String text = value.toString();
        if (StringUtils.isBlank(text)) {
            return null;
        }

        Object result = null;

        if (StringUtils.isNotBlank(text)) {
            text = text.trim();

            if ("null".equals(text)) {
                return null;
            } else {
                int pos = text.indexOf(' ');
                if (pos > 0) {
                    text = text.substring(0, pos);
                }

                try {
                    result = new java.sql.Date(parseDate(text).getTime());
                } catch (ParseException e) {
                    throw new BindParamException(e);
                }
            }

        }

        return result;
    }
}
