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.pagestyle"},
            {StyleLoader.BUNDLE_PREVIEW, "mobile.app.preview"},
            {StyleLoader.BUNDLE_ABUSEFILTER, "mobile.app.pagestyle"}
    };

    // 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();
        for (String[] styleSpec : STYLE_SPECS) {
            String url = getRemoteURLFor(styleSpec[1]);
            try {
                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()));
            } catch (FileNotFoundException e) {
                // This doesn't actually seem to happen ever?
                throw new RuntimeException(e);
            } catch (IOException e) {
                // FIXME: Do not crash!
                throw new RuntimeException(e);
            }
        }

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit();

    }

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

@@ -2032,24 +2032,42 @@
 nContext();%0A
+        try %7B%0A    
         for 
@@ -2099,24 +2099,28 @@
 LE_SPECS) %7B%0A
+    
             
@@ -2167,30 +2167,16 @@
 %5D);%0A    
-        try %7B%0A
         
@@ -2261,16 +2261,20 @@
 IVATE);%0A
+    
         
@@ -2381,16 +2381,20 @@
         
+    
 fo.close
@@ -2393,24 +2393,28 @@
 fo.close();%0A
+    
             
@@ -2546,32 +2546,432 @@
 );%0A            %7D
+%0A%0A            //if any of the above code throws an exception, the following last-updated date will not%0A            //be updated, so the task will be retried on the next go.%0A            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);%0A            prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit();%0A%0A        %7D
  catch (FileNotF
@@ -2981,36 +2981,32 @@
 dException e) %7B%0A
-    
             // T
@@ -3051,36 +3051,32 @@
 er?%0A            
-    
 throw new Runtim
@@ -3094,28 +3094,24 @@
 e);%0A        
-    
 %7D catch (IOE
@@ -3136,20 +3136,16 @@
         
-    
 // FIXME
@@ -3150,55 +3150,159 @@
 ME: 
-Do not crash!%0A                throw new Runtime
+better error feedback?%0A            Log.d(%22StyleFetcherTask%22, e.getMessage());%0A            e.printStackTrace();%0A        %7D catch (HttpRequest.HttpRequest
 Exce
@@ -3298,36 +3298,37 @@
 RequestException
-(e);
+ e) %7B
 %0A            %7D%0A 
@@ -3328,29 +3328,53 @@
     
-%7D%0A    
+// FIXME: better error feedback?%0A
     
-%7D%0A%0A
         
 Shar
@@ -3373,209 +3373,93 @@
     
-SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);%0A        prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit();%0A
+Log.d(%22StyleFetcherTask%22, e.getMessage());%0A            e.printStackTrace();%0A        %7D
 %0A   

Fix crash when there's no network during StyleFetcherTask.