package org.springblade.modules.app.config;

import com.wn.common.tools.date.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author created by gd
 * @date 2018/6/14
 */

@Slf4j
@Configuration
public class ConverterConfig {
    private static final List<String> formarts = new ArrayList<>(2);

    static {
        formarts.add(0, "yyyy-MM-dd");
        formarts.add(1, "HH:mm:ss");
        formarts.add(2, "yyyy-MM-dd HH:mm:ss");
    }

    @Bean
    public Converter<String, Date> addNewConvert() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                String value = source.trim();
                if ("".equals(value)) {
                    return null;
                }
                if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
                    return DateUtils.parse(source, formarts.get(0));
                } else if (source.matches("^\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
                    return DateUtils.parse(source, formarts.get(1));
                } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
                    return DateUtils.parse(source, formarts.get(2));
                } else if (source.matches("^\\d+$")) {
                    Long lDate = new Long(source);
                    return new Date(lDate);
                } else {
                    throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
                }
            }
        };
    }

}
