package eu.eudat.depositinterface.dataverserepository.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@Service("dataverseConfigLoader")
public class ConfigLoaderImpl implements ConfigLoader{
    private static final Logger logger = LoggerFactory.getLogger(ConfigLoaderImpl.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    private DataverseConfig dataverseConfig;

    @Autowired
    private Environment environment;

    @Override
    public DataverseConfig getDataverseConfig() {
        if(dataverseConfig == null){
            try{
                dataverseConfig = mapper.readValue(getStreamFromPath(environment.getProperty("configuration.dataverse")), DataverseConfig.class);
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }
        return dataverseConfig;
    }

    private InputStream getStreamFromPath(String filePath) {
        try {
            return new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            logger.info("loading from classpath");
            return getClass().getClassLoader().getResourceAsStream(filePath);
        }
    }
}
