package me.devsaki.hentoid.parsers;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import me.devsaki.hentoid.database.domains.Content;
import timber.log.Timber;

import static me.devsaki.hentoid.util.HttpHelper.getOnlineDocument;

/**
 * Created by neko on 08/07/2015.
 * Handles parsing of content from hitomi.la
 */
public class HitomiParser extends BaseParser {

    // Reproduction of the Hitomi.la Javascript to find the hostname of the image server (see subdomain_from_url@reader.js)
    private final static int NUMBER_OF_FRONTENDS = 2;
    private final static String HOSTNAME_SUFFIX = "a";
    private final static char HOSTNAME_PREFIX_BASE = 97;

    @Override
    protected List<String> parseImages(Content content) throws Exception {
        List<String> result = new ArrayList<>();

        Document doc = getOnlineDocument(content.getReaderUrl());
        if (doc != null) {
            Timber.d("Parsing: %s", content.getReaderUrl());
            Elements imgElements = doc.select(".img-url");
            // New Hitomi image URLs starting from june 2018
            //  If book ID is even, starts with 'aa'; else starts with 'ba'
            int referenceId = Integer.parseInt(content.getUniqueSiteId()) % 10;
            if (1 == referenceId)
                referenceId = 0; // Yes, this is what Hitomi actually does (see common.js)
            String imageHostname = Character.toString((char) (HOSTNAME_PREFIX_BASE + (referenceId % NUMBER_OF_FRONTENDS))) + HOSTNAME_SUFFIX;

            for (Element element : imgElements) {
                result.add("https:" + element.text().replace("//g.", "//" + imageHostname + "."));
            }
        }

        return result;
    }
}

@@ -1474,24 +1474,25 @@
 ng image
-Hostname
+Subdomain
  = Chara
@@ -1640,24 +1640,114 @@
 Elements) %7B%0A
+                result.add(%22https:%22 + replaceHostWith(element.text(), imageSubdomain));%0A//
             
@@ -1819,16 +1819,17 @@
 mage
-Hostname
+Subdomain
  + %22
@@ -1887,11 +1887,335 @@
 t;%0A    %7D
+%0A%0A    private String replaceHostWith(String url, String newSubdomain) %7B%0A        // Get the beginning and end of subdomain%0A        int subdomainBegin = 2; // Just after '//'%0A        int subdomainEnd = url.indexOf(%22.hitomi%22);%0A%0A        return url.substring(0, subdomainBegin) + newSubdomain + url.substring(subdomainEnd);%0A    %7D
 %0A%7D%0A

Fix images not found for certain Hitomi books