package de.jeyp91;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.google.common.collect.HashBiMap;
import com.google.common.io.Resources;
import de.jeyp91.gists.GistProvider;
import org.apache.logging.log4j.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class TeamIDMatcher {

    private static HashBiMap<Integer, Integer> ids = null;
    private static Logger logger = LogManager.getLogger(TeamIDMatcher.class);

    private static void initBiMap() {
        ids = HashBiMap.create();
        GistProvider prov = GistProvider.getInstance();
        JSONArray teams = prov.getTeamIdMatcher();
        
        for(Object team:teams) {
            int tippligaID = ((Long)((JSONObject) team).get("tippligaID")).intValue();
            int openligaDBID = ((Long) ((JSONObject) team).get("apiFootballID")).intValue();
            ids.put(tippligaID, openligaDBID);
        }
    }

    public static Integer getApiFootballIdFromTippligaId(int id) {
        if(ids == null) {
            initBiMap();
        }
        if(ids.containsKey(id)) {
            return ids.get(id);
        } else {
            logger.error("Tippliga ID: " + String.valueOf(id) + " not in ID Matcher.");
            StatusHolder.setError();
            return null;
        }
    }

    public static Integer getTippligaIdFromApiFootballId(Integer id) {
        if(id == null) return null;
        if(ids == null) {
            initBiMap();
        }
        if(ids.inverse().containsKey(id)) {
            return ids.inverse().get(id);
        } else {
            logger.error("API Football ID: " + String.valueOf(id) + " not in ID Matcher.");
            StatusHolder.setError();
            return null;
        }
    }
}