package eu.eudat.depositinterface.zenodorepository.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.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    private List<DOIFunder> doiFunders = new ArrayList<>();
    private ZenodoConfig zenodoConfig;

    @Autowired
    private Environment environment;

    @Override
    public List<DOIFunder> getDOIFunders() {
        if (doiFunders == null || doiFunders.isEmpty()) {
            try {
                List<Map<String, Object>> tempdoiFunders = mapper.readValue(getStreamFromPath(environment.getProperty("configuration.doi_funder")), List.class);
                doiFunders = tempdoiFunders.stream().map(map -> mapper.convertValue(map, DOIFunder.class) ).collect(Collectors.toList());
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }
        return doiFunders;
    }

    @Override
    public ZenodoConfig getZenodoConfig() {
        if (zenodoConfig == null) {
            try {
                zenodoConfig = mapper.readValue(getStreamFromPath("zenodo.json"), ZenodoConfig.class);
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }
        return zenodoConfig;
    }

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