package me.devsaki.hentoid.activities.websites;

import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.listener.ResultListener;
import me.devsaki.hentoid.retrofit.HentaiCafeServer;
import timber.log.Timber;

import static me.devsaki.hentoid.enums.Site.HENTAICAFE;

/**
 * Created by avluis on 07/21/2016.
 * Implements Hentai Cafe source
 */
public class HentaiCafeActivity extends BaseWebActivity {

    private static final String DOMAIN_FILTER = "hentai.cafe";
    private static final String GALLERY_FILTER = "//hentai.cafe/[A-Za-z0-9\\-_]+/";

    Site getStartSite() {
        return Site.HENTAICAFE;
    }


    @Override
    protected CustomWebViewClient getWebClient() {
        CustomWebViewClient client = new HentaiCafeWebViewClient(GALLERY_FILTER, this);
        client.restrictTo(DOMAIN_FILTER);
        return client;
    }

    private class HentaiCafeWebViewClient extends CustomWebViewClient {

        HentaiCafeWebViewClient(String filteredUrl, ResultListener<Content> listener) {
            super(filteredUrl, listener);
        }

        @Override
        protected void onGalleryFound(String url) {
            if (url.contains(HENTAICAFE.getUrl() + "/78-2/") ||       // ignore tags page
                    url.contains(HENTAICAFE.getUrl() + "/artists/")) {    // ignore artist page
                return;
            }

            String[] galleryUrlParts = url.split("/");
            compositeDisposable.add(HentaiCafeServer.API.getGalleryMetadata(galleryUrlParts[galleryUrlParts.length - 1])
                    .subscribe(
                            metadata -> listener.onResultReady(metadata.toContent(), 1), throwable -> {
                                Timber.e(throwable, "Error parsing content.");
                                listener.onResultFailed("");
                            })
            );
        }
    }
}

@@ -42,16 +42,41 @@
 sites;%0A%0A
+import android.net.Uri;%0A%0A
 import m
@@ -613,24 +613,14 @@
 fe/%5B
-A-Za-z0-9%5C%5C-_
+%5E/
 %5D+/
+$
 %22;%0A%0A
@@ -1210,28 +1210,34 @@
     if (
-url.contains
+    url.startsWith
 (HENTAIC
@@ -1265,10 +1265,10 @@
 /%22) 
-%7C%7C
+  
     
@@ -1313,21 +1313,26 @@
     
+ %7C%7C
  url.
-contains
+startsWith
 (HEN
@@ -1362,19 +1362,16 @@
 tists/%22)
-) %7B
     // i
@@ -1384,24 +1384,150 @@
 artist page%0A
+                    %7C%7C url.startsWith(HENTAICAFE.getUrl() + %22/?s=%22)         // ignore text search results%0A                ) %7B%0A
             
@@ -1684,16 +1684,27 @@
 etadata(
+Uri.decode(
 galleryU
@@ -1739,16 +1739,17 @@
 th - 1%5D)
+)
 %0A       

Rework Hentai Cafe gallery regex because of #243 and #244