+/*
+ * Copyright (c) 2019-2020. Developed by Hedgecode.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.hedgecode.chess.scanner.portal;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.hedgecode.chess.scanner.ChessHogScannerException;
+import org.hedgecode.chess.scanner.entity.PGNGame;
+import org.hedgecode.chess.scanner.entity.PGNTournament;
+import org.hedgecode.chess.scanner.regex.RegexMatcherResult;
+import org.hedgecode.chess.scanner.regex.RegexResult;
+
+/**
+ * ChessGamesScanner
+ *
+ * @author Dmitry Samoshin aka gotty
+ */
+public class ChessGamesScanner extends AbstractSettingsScanner {
+
+ private static final String SETTINGS_FILENAME = "chessgames.settings";
+
+ @Override
+ protected String getResourceName() {
+ return SETTINGS_FILENAME;
+ }
+
+ @Override
+ public PGNTournament getTournament(String tournamentId) throws ChessHogScannerException {
+ PGNTournament tournament = new PGNTournament(tournamentId);
+ assignTournamentGames(tournament);
+ return tournament;
+ }
+
+ @Override
+ public PGNTournament findTournament(String tournamentName) throws ChessHogScannerException {
+ RegexResult result = matchRequest(
+ assignUrl(
+ tournamentName, true
+ ),
+ new RegexMatcherResult(
+ getSettings().getTournamentQueryUrlRegex(),
+ true,
+ true
+ )
+ );
+ PGNTournament tournament = null;
+ for (Map.Entry<String, String> entry : result.resultMap().entrySet()) {
+ if (entry.getValue().contains(tournamentName)) { // todo: contains?
+ tournament = new PGNTournament(
+ entry.getKey(),
+ entry.getValue()
+ );
+ }
+ }
+ if (tournament != null) {
+ assignTournamentGames(tournament);
+ }
+ return tournament;
+ }
+
+ @Override
+ public PGNGame getGame(String gameId) throws ChessHogScannerException {
+ String pgn = request(
+ assignUrl(gameId)
+ );
+ return new PGNGame(
+ gameId, pgn
+ );
+ }
+
+ private void assignTournamentGames(PGNTournament tournament) throws ChessHogScannerException {
+ tournament.clearGames();
+ List<String> gamesId = new ArrayList<>();
+
+ List<String> pageGamesId;
+ int pageId = 0;
+ do {
+ pageGamesId = matchRequest(
+ assignUrl(
+ tournament.id(),
+ Integer.toString(++pageId)
+ ),
+ getSettings().getTournamentGamesUrlRegex(),
+ false
+ );
+ gamesId.addAll(
+ pageGamesId
+ );
+ } while (!pageGamesId.isEmpty());
+
+ for (String gameId : gamesId) {
+ tournament.addGame(
+ getGame(gameId)
+ );
+ }
+ }
+
+}