package ru.yandex.qe.spring.converters;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * User: bgleb
 */
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService> {
    private final GenericConversionService conversionService;

    @Autowired(required = false)
    private Set<Converter> converters;

    public ConversionServiceFactoryBean() {
        conversionService = new DefaultConversionService();
    }

    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        if (this.converters != null) {
            ConversionServiceFactory.registerConverters(this.converters, this.conversionService);
        }
    }

    @Override
    public ConversionService getObject() throws Exception {
        return conversionService;
    }

    @Override
    public Class<?> getObjectType() {
        return GenericConversionService.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
