package pl.minidmnv.apple.source.fixture.repository;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Optional;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import pl.minidmnv.apple.source.exception.FSConnectionException;

/**
 * @author mnicinski.
 */
@Repository
public class FSFixtureRepository implements FixtureRepository {

	private static final Logger log = LoggerFactory.getLogger(FSFixtureRepository.class);
	private static final String ROOT_URL = "http://www.flashscore.pl/";

	@Override public Optional<Document> getUpcomingFixturesDocument() {
		return getSiteDocument(ROOT_URL + "pilka-nozna/polska/ekstraklasa/spotkania/");
	}

	@Override
	public Optional<Document> getFixtureHeadDetails(String fixtureId) {
		return getSiteDocument(MessageFormat.format(ROOT_URL + "mecz/{0}/#h2h;overall", fixtureId));
	}

	private Optional<Document> getSiteDocument(String url) {
		log.info("url: " + url);
		Document siteDocument = null;
		try {
			siteDocument = Jsoup.connect(url).get();
		} catch (Exception e) {
			log.error("Wystąpił błąd podczas połączenia FlashScore", e);
			throw new FSConnectionException();
		}

		log.debug("Zwracam odpowiedź: " + siteDocument.outerHtml());
		return Optional.ofNullable(siteDocument);
	}

}

@@ -51,36 +51,8 @@
 y;%0A%0A
-import java.io.IOException;%0A
 impo
@@ -267,24 +267,25 @@
 Repository;%0A
+%0A
 import pl.mi
@@ -600,16 +600,95 @@
 re.pl/%22;
+%0A%09private static final String ROOT_FEED_URL = %22http://d.flashscore.pl/x/feed/%22;
 %0A%0A%09@Over
@@ -971,36 +971,33 @@
 OOT_
+FEED_
 URL + %22
-mecz/%7B0%7D/#h2h;overall
+d_hh_%7B0%7D_pl_1
 %22, f
@@ -1124,15 +1124,8 @@
 ment
- = null
 ;%0A%09%09
@@ -1166,16 +1166,118 @@
 ect(url)
+%0A%09%09%09%09%09.referrer(%22http://d.flashscore.pl/x/feed/proxy-local%22)%0A%09%09%09%09%09.header(%22X-Fsign%22, %22SW9D1eZo%22)%0A%09%09%09%09%09
 .get();%0A
@@ -1496,16 +1496,8 @@
 l.of
-Nullable
 (sit

Fix H2H document for fixture details fetching issues.