package org.wikipedia.bridge;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
import org.wikipedia.Site;
import org.wikipedia.Utils;
import org.wikipedia.WikipediaApp;
import org.wikipedia.recurring.RecurringTask;

import java.io.*;
import java.net.URLEncoder;
import java.util.Date;

public class StyleFetcherTask extends RecurringTask {

    private static final String[][] STYLE_SPECS = {
            {StyleLoader.BUNDLE_PAGEVIEW, "mobile.app.pagestyles.android"},
            {StyleLoader.BUNDLE_PREVIEW, "mobile.app.preview"},
            {StyleLoader.BUNDLE_ABUSEFILTER, "mobile.app.pagestyles.android"}
    };

    // The 'l' suffix is needed because stupid Java overflows constants otherwise
    private static final long RUN_INTERVAL_MILLI =  24L * 60L * 60L * 1000L;

    public StyleFetcherTask(Context context) {
        super(context);
    }

    @Override
    protected boolean shouldRun(Date lastRun) {
        return System.currentTimeMillis() - lastRun.getTime() >= RUN_INTERVAL_MILLI;
    }

    private String getRemoteURLFor(String modules) {
        Site site = ((WikipediaApp) context.getApplicationContext()).getPrimarySite();
        try {
            return String.format(
                    // This points to betalabs, which shows the master version of the styles used
                    // Should switch to production bits URL before release.
                    "http://bits.beta.wmflabs.org/%s.wikipedia.beta.wmflabs.org/load.php?debug=true&lang=en&modules=%s&only=styles&skin=vector&version=&*",
                    site.getLanguage(),
                    URLEncoder.encode(modules, "utf-8")
            );
        } catch (UnsupportedEncodingException e) {
            // This does not happen.
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void run(Date lastRun) {
        WikipediaApp app = (WikipediaApp) context.getApplicationContext();
        try {
            for (String[] styleSpec : STYLE_SPECS) {
                String url = getRemoteURLFor(styleSpec[1]);
                    OutputStream fo = context.openFileOutput(styleSpec[0], Context.MODE_PRIVATE);
                    Utils.copyStreams(HttpRequest.get(url).userAgent(app.getUserAgent()).stream(), fo);
                    fo.close();
                    Log.d("Wikipedia", String.format("Downloaded %s into %s", url, context.getFileStreamPath(styleSpec[0]).getAbsolutePath()));
            }

            //if any of the above code throws an exception, the following last-updated date will not
            //be updated, so the task will be retried on the next go.
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit();

        } catch (FileNotFoundException e) {
            // This doesn't actually seem to happen ever?
            throw new RuntimeException(e);
        } catch (IOException e) {
            // FIXME: better error feedback?
            Log.d("StyleFetcherTask", e.getMessage());
            e.printStackTrace();
        } catch (HttpRequest.HttpRequestException e) {
            // FIXME: better error feedback?
            Log.d("StyleFetcherTask", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    protected String getName() {
        return "style-fetcher";
    }
}

@@ -2180,16 +2180,290 @@
 pec%5B1%5D);
+%0A%0A                HttpRequest request = HttpRequest.get(url).userAgent(app.getUserAgent());%0A                // Only overwrite files if we get a 200%0A                // This prevents empty style files from being used when betalabs goes down%0A                if (request.ok()) %7B
 %0A       
@@ -2595,71 +2595,204 @@
 ams(
-HttpR
+r
 equest.
-get(url).userAgent(app.getUserAgent()).stream(), fo
+stream(), fo);%0A                    fo.close();%0A                    Log.d(%22Wikipedia%22, String.format(%22Downloaded %25s into %25s%22, url, context.getFileStreamPath(styleSpec%5B0%5D).getAbsolutePath())
 );%0A 
@@ -2802,39 +2802,32 @@
             
-    fo.close();
+%7D else %7B
 %0A           
@@ -2865,34 +2865,42 @@
 ing.format(%22
-D
+Failed to d
 ownload
-ed
  %25s into %25s%22
@@ -2959,32 +2959,78 @@
 solutePath()));%0A
+                    return;%0A                %7D%0A
             %7D%0A%0A 

Make downloading styles more robust