package de.jeyp91.apifootball; import java.util.ArrayList; import java.util.HashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import de.jeyp91.S3Provider; 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 = LoggerFactory.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(this.season, 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(this.season, league); for (APIFootballMatch singleMatch : allMatches) { if (singleMatch.getMatchday() == matchday) { matchesOfMatchday.add(singleMatch); } } return matchesOfMatchday; } public ArrayList getMatchesFromLeagueFromFile(int season, int leagueId) { ArrayList matchesList = new ArrayList<>(); S3Provider prov = new S3Provider(); if(!this.matches.containsKey(leagueId)) { this.matches.put(leagueId, prov.getFixturesJSONFromS3(season, leagueId)); } JSONObject matchesObject = this.matches.get(leagueId); JSONArray matchArray = (JSONArray) (matchesObject.get("response")); 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(this.season, leagueId)); } return this.rounds.get(leagueId); } public JSONObject getTeamsForLeague(int season, int league) throws Exception { String requestPath = "teams"; String content = new APIFootballUpdater().getRawData(requestPath, season, league); 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; } }