package de.jeyp91.apifootball; import de.jeyp91.S3Provider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.util.ArrayList; import java.util.HashMap; public class APIFootballConnector { private static APIFootballConnector conn = null; private final int season; private final HashMap rounds = new HashMap<>(); private final HashMap matches = new HashMap<>(); private static final Logger logger = LogManager.getLogger(APIFootballConnector.class); private APIFootballConnector(int season) { this.season = season; } public static APIFootballConnector getAPIFootballConnectorInstance(int season) { if(conn == null) { conn = new APIFootballConnector(season); } return conn; } public APIFootballMatch getMatchDataByLeagueAndMatchID(int league, int id) { APIFootballMatch matchWithID = null; ArrayList allMatches = getMatchesFromLeagueFromFile(league); for (APIFootballMatch singleMatch : allMatches) { if (singleMatch.getAPIFootBallMatchID() == id) { matchWithID = singleMatch; break; } } return matchWithID; } public ArrayList getMatchDataByLeagueAndMatchday(int league, int matchday) { ArrayList matchesOfMatchday = new ArrayList<>(); ArrayList allMatches = getMatchesFromLeagueFromFile(league); for (APIFootballMatch singleMatch : allMatches) { if (singleMatch.getMatchday() == matchday) { matchesOfMatchday.add(singleMatch); } } return matchesOfMatchday; } public ArrayList getMatchesFromLeagueFromFile(int leagueId) { ArrayList matchesList = new ArrayList<>(); S3Provider prov = new S3Provider(); if(!this.matches.containsKey(leagueId)) { this.matches.put(leagueId, prov.getFixturesJSONFromS3(leagueId)); } JSONObject matches = this.matches.get(leagueId); JSONArray matchArray = (JSONArray) (((JSONObject)matches.get("api")).get("fixtures")); for(int i = 0; i < matchArray.size(); i++) { try { APIFootballMatch match = new APIFootballMatch((JSONObject) matchArray.get(i), this.season); matchesList.add(match); } catch (Exception e) { logger.error(e.getMessage()); } } return matchesList; } public JSONObject getMatchdays(int leagueId) { S3Provider prov = new S3Provider(); if(!this.rounds.containsKey(leagueId)) { this.rounds.put(leagueId, prov.getRoundsJSONFromS3(leagueId)); } return this.rounds.get(leagueId); } public JSONObject getTeamsForLeague(int league) throws Exception { String url = "https://v2.api-football.com/teams/league/" + league; String content = new APIFootballUpdater().getRawData(url); return stringToJSONObject(content); } public static JSONObject stringToJSONObject(String rawData) { JSONParser parser = new JSONParser(); JSONObject data = null; try { data = (JSONObject) parser.parse(rawData); } catch (Exception e) { /* TODO */ e.printStackTrace(); } return data; } }