package pirateboat.torrent;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import pirateboat.utilities.HttpHelper;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class RARBG extends HttpUser implements TorrentSearchEngine {
    public RARBG(HttpHelper httpHelper) {
        super(httpHelper);
    }

    @Override
    public List<Torrent> searchTorrents(String searchName) {
        CopyOnWriteArrayList<Torrent> torrentList = new CopyOnWriteArrayList<>();

        String resultString = null;
        resultString = httpHelper.getPage(buildSearchUrl(searchName));

        torrentList.addAll(parseTorrentsOnResultPage(resultString, searchName));
        torrentList.sort(TorrentHelper.torrentSorter);
        return torrentList;
    }

    @Override
    public String getBaseUrl() {
        return "http://rarbg.to";
    }

    @Override
    public String getSearchPage() {
        return buildSearchUrl("test");
    }

    private String buildSearchUrl(String searchName) {
        return String.format(getBaseUrl() + "/torrents.php?search=%s&order=seeders&by=DESC", URLEncoder.encode(searchName, StandardCharsets.UTF_8));
    }

    private List<Torrent> parseTorrentsOnResultPage(String pageContent, String searchName) {

        Document doc = Jsoup.parse(pageContent);

        Elements torrentsOnPage = doc.select(".lista2");
        return torrentsOnPage.stream()
                .map(Node::toString)
                .map(elementString -> extractSubUrl(elementString))
                .map(url -> parseTorrentsOnSubPage(httpHelper.getPage(url), searchName))
                .collect(Collectors.toList());
    }

    private Torrent parseTorrentsOnSubPage(String page, String searchName) {
        Document doc = Jsoup.parse(page);
        final Torrent torrent = new Torrent(this.getClass().getSimpleName());
        torrent.name = doc.title().replaceAll(" Torrent download","");
        torrent.magnetUri = doc.select("a[href*=magnet]")
                .stream()
                .map(element -> element.attributes().get("href"))
                .filter(Objects::nonNull)
                .findFirst().orElse(null);
        final String text = doc.text();

        torrent.size = TorrentHelper.cleanNumberString(getValueBetweenStrings(text, "Size : ","Show Files"));
        torrent.lsize = TorrentHelper.extractTorrentSizeFromString(torrent);

        torrent.seeder = Integer.parseInt(getValueBetweenStrings(text, "Seeders : "," ,"));
        torrent.leecher = Integer.parseInt(getValueBetweenStrings(text, "Leechers : "," ,"));
        TorrentHelper.evaluateRating(torrent, searchName);
        return torrent;
    }

    private String extractSubUrl(String elementString) {
        Pattern subUrlPattern = Pattern.compile("href=\"(\\/torrent\\/[A-Za-z0-9]+)\"");
        Matcher matcher = subUrlPattern.matcher(elementString);
        while (matcher.find()) {
            return getBaseUrl() + matcher.group(1);
        }
        return null;
    }

    private String getValueBetweenStrings(String input, String firstString, String secondString){
        Pattern betweenPattern = Pattern.compile(firstString+"(.*)"+secondString);
        Matcher matcher = betweenPattern.matcher(input);
        while (matcher.find()) {
            return getBaseUrl() + matcher.group(1);
        }
        return "";
    }

}

@@ -2086,36 +2086,15 @@
 nt(t
-his.getClass().getSimpleName
+oString
 ());
@@ -2548,16 +2548,23 @@
  Files%22)
+.trim()
 );%0A     
@@ -2717,32 +2717,39 @@
 eeders : %22,%22 ,%22)
+.trim()
 );%0A        torre
@@ -2826,16 +2826,23 @@
  %22,%22 ,%22)
+.trim()
 );%0A     
@@ -3618,10 +3618,111 @@
 %0A    %7D%0A%0A
+    @Override%0A    public String toString() %7B%0A        return this.getClass().getSimpleName();%0A    %7D%0A%0A%0A
 %7D%0A

fix toString for SearchEngineClass