package com.rarchives.ripme.ripper.rippers;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.rarchives.ripme.ripper.AlbumRipper;

public class EHentaiRipper extends AlbumRipper {
    private static final String DOMAIN = "g.e-hentai.org", HOST = "e-hentai";
    private static final Logger logger = Logger.getLogger(EHentaiRipper.class);

    private Document albumDoc = null;

    private URL prevUrl = null;
    private URL cursorUrl = null;
    private Document cursorDoc = null;

    public EHentaiRipper(URL url) throws IOException {
        super(url);
    }

    @Override
    public String getHost() {
        return HOST;
    }

    public URL sanitizeURL(URL url) throws MalformedURLException {
        return url;
    }

    public String getAlbumTitle(URL url) throws MalformedURLException {
        try {
            // Attempt to use album title as GID
            if (albumDoc == null) {
                albumDoc = Jsoup.connect(url.toExternalForm()).get();
            }
            Elements elems = albumDoc.select("#gn");
            return HOST + "_" + elems.get(0).text();
        } catch (Exception e) {
            // Fall back to default album naming convention
            e.printStackTrace();
        }
        return super.getAlbumTitle(url);
    }

    @Override
    public String getGID(URL url) throws MalformedURLException {
        Pattern p;
        Matcher m;

        System.out.println(url);

        p = Pattern.compile("^.*g\\.e-hentai\\.org/g/[0-9]+/[a-fA-F0-9]+)/$");
        m = p.matcher(url.toExternalForm());
        if (m.matches()) {
            return m.group(1);
        }

        throw new MalformedURLException(
                "Expected g.e-hentai.org gallery format: "
                        + "http://g.e-hentai.org/g/####/####/"
                        + " Got: " + url);
    }

    @Override
    public void rip() throws IOException {
        int index = 0;
        logger.info("    Retrieving " + this.url.toExternalForm());
        if (albumDoc == null) {
            albumDoc = Jsoup.connect(this.url.toExternalForm()).get();
        }
        if (cursorDoc == null) {
            Elements select = albumDoc.select("#gdt > .gdtm");
            Element first = select.first();
            String href = first.select("a").attr("href");
            cursorUrl = new URL(href);
            System.out.println(cursorUrl);
        }

        while (!cursorUrl.equals(prevUrl)) {
            cursorDoc = Jsoup.connect(this.cursorUrl.toExternalForm()).get();

            Elements a = cursorDoc.select(".sni > a");
            Elements img = a.select("img");

            String imgsrc = img.attr("src");
            addURLToDownload(new URL(imgsrc), String.format("%03d_", index));

            String href = a.attr("href");

            prevUrl = cursorUrl;
            cursorUrl = new URL(href);

            index++;
        }

        waitForThreads();
    }

    public boolean canRip(URL url) {
        return url.getHost().endsWith(DOMAIN);
    }
}
@@ -34,24 +34,45 @@
 r.rippers;%0A%0A
+import java.io.File;%0A
 import java.
@@ -2621,51 +2621,8 @@
 f);%0A
-            System.out.println(cursorUrl);%0A
     
@@ -2619,32 +2619,32 @@
 ref);%0A        %7D%0A
+
 %0A        while (
@@ -2893,24 +2893,572 @@
 ttr(%22src%22);%0A
+            Pattern p = Pattern.compile(%22%5Ehttp://.*/ehg/image.php.*&n=(%5B%5E&%5D+).*$%22);%0A            Matcher m = p.matcher(imgsrc);%0A            if (m.matches()) %7B%0A                // Manually discover filename from URL%0A                String savePath = this.workingDir + File.separator;%0A                savePath += String.format(%22%2503d_%25s%22, index + 1, m.group(1));%0A                addURLToDownload(new URL(imgsrc), new File(savePath));%0A            %7D%0A            else %7B%0A                // Provide prefix and let the AbstractRipper %22guess%22 the filename%0A    
             
@@ -3519,19 +3519,37 @@
 %22, index
-));
+ + 1));%0A            %7D
 %0A%0A      

Fix ehentai "image.php" filenames. Closes #37