package com.github.cjnosal.yats.providers;

import android.text.TextUtils;

import com.github.cjnosal.yats.network.AuthManager;
import com.github.cjnosal.yats.network.models.AuthResponse;
import com.github.cjnosal.yats.network.models.subreddit.Link;
import com.github.cjnosal.yats.network.models.subreddit.SubredditSearchResponse;
import com.github.cjnosal.yats.network.services.RedditContentService;

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

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;
import timber.log.Timber;

public class RedditProvider {

    private static final String DEFAULT_SUB = "pics";
    private static final int NUM_IMAGES = 10;

    @Inject
    RedditContentService redditService;

    @Inject
    AuthManager authManager;

    boolean isLastPage = false;
    String lastImage = null;

    @Inject
    public RedditProvider() {
    }

    public Observable<List<String>> getImageUrls() {

        if (isLastPage) {
            return Observable.empty();
        } else if (authManager.isAuthenticated()) {
            return getUrlObservable();
        } else {
            return authManager.fetchAuthToken().flatMap(new Func1<AuthResponse, Observable<List<String>>>() {
                @Override
                public Observable<List<String>> call(AuthResponse authResponse) {
                    return getUrlObservable();
                }
            });
        }
    }

    private Observable<List<Link>> getLinkObservable() {
        return redditService.searchSubreddit(authManager.getOauthHeader(), DEFAULT_SUB, NUM_IMAGES, getTimeQuery(), lastImage)
                .flatMap(new Func1<SubredditSearchResponse, Observable<Link>>() {
                    @Override
                    public Observable<Link> call(SubredditSearchResponse subredditSearchResponse) {

                        String after = subredditSearchResponse.getListingData().getAfter();
                        if (TextUtils.isEmpty(after)) {
                            isLastPage = true;
                            lastImage = null;
                        } else {
                            isLastPage = false;
                            lastImage = after;
                        }
                        return Observable.from(subredditSearchResponse.getListingData().getLinks());
                    }
                })
                .toList();
    }

    private Observable<List<String>> getUrlObservable() {
        return getLinkObservable().flatMap(new Func1<List<Link>, Observable<String>>() {
            @Override
            public Observable<String> call(List<Link> links) {
                List<String> urls = new ArrayList<>(links.size());
                for (Link link : links) {
                    String url = getImageUrl(link);
                    if (!TextUtils.isEmpty(url)) {
                        urls.add(url);
                    }
                }
                return Observable.from(urls);
            }
        }).toList();
    }

    private String getImageUrl(Link link) {

        String linkUrl = link.getData().getUrl();

        String mediaUrl = null;
        if (link.getData().getMedia() != null) {
            mediaUrl = link.getData().getMedia().getOembed().getThumbnailUrl();
        }

        String previewUrl = null;
        if (link.getData().getPreview() != null) {
            previewUrl = link.getData().getPreview().getImages().get(0).getSource().getUrl();
        }

        String url = null;
        if (hasImageExtension(linkUrl)) {
            url = linkUrl;
            Timber.d("Using link url  %s", url);
        } else if (hasImageExtension(mediaUrl)) {
            url = mediaUrl;
            Timber.d("Using media url %s", url);
        } else if (hasImageExtension(previewUrl)) {
            url = previewUrl;
            Timber.d("Using preview url %s", url);
        } else {
            Timber.d("Skipping %s", linkUrl);
        }

        return url;
    }

    private boolean hasImageExtension(String url) {
        return !TextUtils.isEmpty(url) && (url.endsWith("png") || url.endsWith("jpg") || url.endsWith("jpeg"));
    }

    private String getTimeQuery() {
        Calendar calendar = Calendar.getInstance();

        // move forward to midnight
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        // subtract a year
        calendar.add(Calendar.YEAR, -1);
        long end = calendar.getTimeInMillis() / 1000;

        // subtract a day
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        long start = calendar.getTimeInMillis() / 1000;

        return String.format("timestamp:%1$s..%2$s", start, end);
    }
}

@@ -395,16 +395,37 @@
 rvice;%0A%0A
+import java.net.URI;%0A
 import j
@@ -3942,86 +3942,579 @@
 lse 
-%7B%0A            Timber.d(%22Skipping %25s%22, linkUrl);%0A        %7D%0A%0A        return url;
+if (tryDirectImgurLink(linkUrl)) %7B%0A            url = linkUrl + %22.jpg%22;%0A            Timber.d(%22Trying direct imgur link %25s%22, url);%0A        %7D else %7B%0A            Timber.d(%22Skipping %25s%22, linkUrl);%0A        %7D%0A%0A        return url;%0A    %7D%0A%0A    private boolean tryDirectImgurLink(String url) %7B%0A        URI uri = URI.create(url);%0A        return uri.getHost().contains(%22imgur.com%22)%0A                && !uri.getPath().contains(%22/gallery/%22) // gallery link%0A                && !uri.getPath().contains(%22/a/%22) // album link%0A                && !uri.getPath().contains(%22,%22); // list of images
 %0A   
@@ -4581,16 +4581,12 @@
     
-return !
+if (
 Text
@@ -4607,16 +4607,125 @@
 url)
- && (url
+) %7B%0A            return false;%0A        %7D else %7B%0A            String lower = url.toLowerCase();%0A            return lower
 .end
@@ -4736,27 +4736,29 @@
 h(%22png%22) %7C%7C 
-url
+lower
 .endsWith(%22j
@@ -4765,19 +4765,21 @@
 pg%22) %7C%7C 
-url
+lower
 .endsWit
@@ -4787,18 +4787,27 @@
 (%22jpeg%22)
-)
 ;
+%0A        %7D
 %0A    %7D%0A%0A

Improve detection of direct image links