package de.fu_berlin.cdv.chasingpictures;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import de.fu_berlin.cdv.chasingpictures.api.Picture;

/**
 * @author Simon
 */
public class PictureDownloader extends AsyncTask<Picture, Object, Void> {
    private static final String TAG = "PictureDownloader";
    private static final int BUFFER_SIZE = 1024 * 100; // 100 KB
    private final File targetDirectory;

    public PictureDownloader(File targetDirectory) {
        this.targetDirectory = targetDirectory;
    }

    @Override
    protected Void doInBackground(Picture... params) {
        for (Picture picture : params) {

            try {
                String fileName = picture.getId() + "_" + picture.getUpdatedAt().getTime();
                File destinationFile = new File(targetDirectory, fileName);

                // If file already exists, skip the download.
                picture.setCachedFile(destinationFile);
                if (destinationFile.exists()) {
                    continue;
                }

                URL url = picture.getASCIIUrl();
                downloadUrlToFile(url, destinationFile);
            } catch (IOException e) {
                Log.e(TAG, Log.getStackTraceString(e));
                picture.setCachedFile(null);
            }
        }
        return null;
    }

    private void downloadUrlToFile(URL url, File destinationFile) throws IOException {
        URLConnection urlConnection = url.openConnection();
        int contentLength = urlConnection.getContentLength();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        FileOutputStream fos = new FileOutputStream(destinationFile);
        byte[] buffer;

        if (contentLength >= 0) {
            buffer = new byte[contentLength];
        } else {
            buffer = new byte[BUFFER_SIZE];
        }

        try {
            int result;
            do {
                result = in.read(buffer);
                if (result > 0)
                    fos.write(buffer, 0, result);
            } while (result > 0);
        } finally {
            in.close();
            fos.close();
        }
    }
}

@@ -253,19 +253,33 @@
 ava.net.
-URL
+HttpURLConnection
 ;%0Aimport
@@ -291,26 +291,16 @@
 .net.URL
-Connection
 ;%0A%0Aimpor
@@ -1629,37 +1629,166 @@
     
-URLConnection urlConnection =
+String location;%0A        HttpURLConnection urlConnection;%0A%0A        // Follow redirects%0A        while (true) %7B%0A            urlConnection = ((HttpURLConnection)
  url
@@ -1804,18 +1804,607 @@
 ection()
+)
 ;%0A
+%0A            /*%0A            urlConnection.setConnectTimeout(15000);%0A            urlConnection.setReadTimeout(15000);%0A            urlConnection.setInstanceFollowRedirects(false);%0A             */%0A%0A            switch (urlConnection.getResponseCode()) %7B%0A                case HttpURLConnection.HTTP_MOVED_PERM:%0A                case HttpURLConnection.HTTP_MOVED_TEMP:%0A                    location = urlConnection.getHeaderField(%22Location%22);%0A                    url = new URL(url, location);  // Deal with relative URLs%0A                    continue;%0A            %7D%0A%0A            break;%0A        %7D%0A%0A
         
@@ -2634,16 +2634,16 @@
 uffer;%0A%0A
+
         
@@ -2661,17 +2661,16 @@
 Length %3E
-=
  0) %7B%0A  

Fix PictureDownloader to follow redirects