package de.jeyp91.googlecalendar;

import com.google.common.io.Resources;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

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

public class CalendarConfigProvider {

    private static JSONObject googleCalendarConfig = null;

    private static JSONObject getGoogleCalendarConfig() {
        if(googleCalendarConfig == null) {
            //JSON parser object to parse read file
            JSONParser jsonParser = new JSONParser();
            URL url = Resources.getResource("Google_Calendar_Config.json");
            String jsonConfig = null;

            try {
                jsonConfig = Resources.toString(url, StandardCharsets.UTF_8);
                //Read JSON file
                googleCalendarConfig = (JSONObject) jsonParser.parse(jsonConfig);

            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }

        }
        return googleCalendarConfig;
    }

    public static String getCalendarUrl(int league) {

        // Overwrite league from 2 to 1 because they share one calendar
        league = league == 2 ? 1 : league;

        JSONObject leagueConfig = (JSONObject) getGoogleCalendarConfig().get(String.valueOf(league));
        return (String) leagueConfig.get("url");
    }

    public static String getCalendarId(int league) {

        // Overwrite league from 2 to 1 because they share one calendar
        league = league == 2 ? 1 : league;

        JSONObject leagueConfig = (JSONObject) getGoogleCalendarConfig().get(String.valueOf(league));
        return (String) leagueConfig.get("id");
    }
}
