package de.danoeh.antennapod.discovery;

import android.content.Context;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.ClientConfig;
import de.danoeh.antennapod.core.service.download.AntennapodHttpClient;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ItunesTopListLoader {
    private final Context context;

    public ItunesTopListLoader(Context context) {
        this.context = context;
    }

    public Single<List<PodcastSearchResult>> loadToplist(int limit) {
        return Single.create((SingleOnSubscribe<List<PodcastSearchResult>>) emitter -> {
            String lang = Locale.getDefault().getLanguage();
            OkHttpClient client = AntennapodHttpClient.getHttpClient();
            String feedString;
            try {
                feedString = getTopListFeed(client, lang, limit);
            } catch (IOException e) {
                feedString = getTopListFeed(client, "us", limit);
            }
            List<PodcastSearchResult> podcasts = parseFeed(feedString);
            emitter.onSuccess(podcasts);
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Single<String> getFeedUrl(PodcastSearchResult podcast) {
        if (!podcast.feedUrl.contains("itunes.apple.com")) {
            return Single.just(podcast.feedUrl)
                    .observeOn(AndroidSchedulers.mainThread());
        }
        return Single.create((SingleOnSubscribe<String>) emitter -> {
            OkHttpClient client = AntennapodHttpClient.getHttpClient();
            Request.Builder httpReq = new Request.Builder()
                    .url(podcast.feedUrl)
                    .header("User-Agent", ClientConfig.USER_AGENT);
            try {
                Response response = client.newCall(httpReq.build()).execute();
                if (response.isSuccessful()) {
                    String resultString = response.body().string();
                    JSONObject result = new JSONObject(resultString);
                    JSONObject results = result.getJSONArray("results").getJSONObject(0);
                    String feedUrl = results.getString("feedUrl");
                    emitter.onSuccess(feedUrl);
                } else {
                    String prefix = context.getString(R.string.error_msg_prefix);
                    emitter.onError(new IOException(prefix + response));
                }
            } catch (IOException | JSONException e) {
                emitter.onError(e);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    private String getTopListFeed(OkHttpClient client, String language, int limit) throws IOException {
        String url = "https://itunes.apple.com/%s/rss/toppodcasts/limit="+limit+"/explicit=true/json";
        Request.Builder httpReq = new Request.Builder()
                .header("User-Agent", ClientConfig.USER_AGENT)
                .url(String.format(url, language));

        try (Response response = client.newCall(httpReq.build()).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            }
            String prefix = context.getString(R.string.error_msg_prefix);
            throw new IOException(prefix + response);
        }
    }

    private List<PodcastSearchResult> parseFeed(String jsonString) throws JSONException {
        JSONObject result = new JSONObject(jsonString);
        JSONObject feed = result.getJSONObject("feed");
        JSONArray entries = feed.getJSONArray("entry");

        List<PodcastSearchResult> results = new ArrayList<>();
        for (int i=0; i < entries.length(); i++) {
            JSONObject json = entries.getJSONObject(i);
            results.add(PodcastSearchResult.fromItunesToplist(json));
        }

        return results;
    }

}

@@ -66,16 +66,42 @@
 ontext;%0A
+import android.util.Log;%0A%0A
 import d
@@ -123,16 +123,16 @@
 apod.R;%0A
-
 import d
@@ -715,16 +715,77 @@
 oader %7B%0A
+    private static final String TAG = %22ITunesTopListLoader%22;%0A
     priv
@@ -1079,20 +1079,23 @@
  String 
-lang
+country
  = Local
@@ -1116,16 +1116,15 @@
 .get
-Language
+Country
 ();%0A
@@ -1296,20 +1296,23 @@
 client, 
-lang
+country
 , limit)
@@ -3206,24 +3206,23 @@
  String 
-language
+country
 , int li
@@ -3324,15 +3324,19 @@
 it=%22
-+
+ + 
 limit
-+
+ + 
 %22/ex
@@ -3354,16 +3354,79 @@
 /json%22;%0A
+        Log.d(TAG, %22Feed URL %22 + String.format(url, country));%0A
         
@@ -3580,16 +3580,15 @@
 rl, 
-language
+country
 ));%0A
@@ -4257,17 +4257,19 @@
 r (int i
-=
+ = 
 0; i %3C e

Use country code instead of language for top itunes feed