package cn.ibizlab.businesscentral.core.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.util.NumberUtils;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;

@Configuration
public class UndefinedConvertConfiguration {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;


    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();


            genericConversionService.addConverter(new Converter<String, Long>() {
                @Override
                public Long convert(String source) {
                    if(StringUtils.compare("undefined",source)==0)
                        return 0l;
                    try{
                        return NumberUtils.parseNumber(source, Long.class);
                    }catch (Exception e){
                        return 0l;
                    }

                }
            }) ;

        }
    }

}
