package cn.com.victorysoft.business.config;

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String, Date> {


    private static final String secondFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String minuteFormat = "yyyy-MM-dd HH:mm";
    private static final String hourFormat = "yyyy-MM-dd HH";
    private static final String dateFormat = "yyyy-MM-dd";
    private static final String timeStampFormat = "^\\d+$";

    @Override
    public Date convert(String value) {

        if(value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
            return null;
        }

        value = value.trim();

        try {
            if (value.contains("-")) {
                SimpleDateFormat formatter;
                if (value.contains(" ")) {
                    if (value.contains(":")) {
                        int length = value.split(":").length;
                        if (length == 2) {
                            formatter = new SimpleDateFormat(minuteFormat);
                        }else {
                            formatter = new SimpleDateFormat(secondFormat);
                        }
                    }else {
                        formatter = new SimpleDateFormat(hourFormat);
                    }
                } else {
                    formatter = new SimpleDateFormat(dateFormat);
                }
                return formatter.parse(value);
            } else if (value.matches(timeStampFormat)) {
                Long lDate = new Long(value);
                return new Date(lDate);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
}