package eu.eudat.models.rda.mapper;

import eu.eudat.models.rda.Language;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

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

	static {
		String json = null;
		try {
			json = new BufferedReader(new InputStreamReader(LanguageRDAMapper.class.getClassLoader().getResource("internal/rda-lang-map.json").openStream(), StandardCharsets.UTF_8))
					.lines().collect(Collectors.joining("\n"));
			langMap.putAll(new org.json.JSONObject(json).toMap());
		} 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();
	}
}
