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

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

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

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

    @Override
    public Object parseText(Object value) throws IllegalArgumentException {
        if (value == null) {
            return null;
        }

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

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

        text = text.trim();

        if ("null".equals(text)) {
            return null;
        }

        Timestamp result = null;

        try {
            int pos = text.indexOf(':');
            if (pos < 0 && text.indexOf("-") < 0) {
                result = new Timestamp(Long.parseLong(text));
            } else if (text.length() > 10) {
                if (text.indexOf(':', pos + 1) > pos) {
                    result = new Timestamp(parseDateTime(text).getTime());
                } else {
                    result = new Timestamp(parseDateTime(text).getTime());
                }
            } else {
                result = new Timestamp(parseDateTime(text).getTime());
            }
        } catch (ParseException ex) {
            throw new BindParamException(ex);
        }

        return result;
    }
}
