package eu.eudat.models.rda.mapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.models.rda.Language;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class LanguageRDAMapper {
	private final static Map<String, Object> langMap = new HashMap<>();
	private static final Logger logger = LoggerFactory.getLogger(LanguageRDAMapper.class);

	static {
		try {
			ObjectMapper mapper = new ObjectMapper();
			InputStreamReader isr = new InputStreamReader(LanguageRDAMapper.class.getClassLoader().getResource("internal/rda-lang-map.json").openStream(), StandardCharsets.UTF_8);
			langMap.putAll(mapper.readValue(isr, LinkedHashMap.class));
			isr.close();

		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public static Language mapLanguageIsoToRDAIso(String code) {
		return langMap.entrySet().stream().map(entry -> {
			if (entry.getValue().toString().equals(code)) {
				return Language.fromValue(entry.getKey());
			} else {
				return null;
			}
		}).filter(Objects::nonNull).findFirst().get();
	}

	public static String mapRDAIsoToLanguageIso(Language lang) {
		return langMap.get(lang.value()).toString();
	}
}
