package us.mikeandwan.photos.services;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import us.mikeandwan.photos.MawApplication;


// TODO: this currently requires external storage, perhaps also allow this to run w/o caching - perhaps thumbnails in internal storage?
public class PhotoStorage {
    private static final String MAW_ROOT = "maw_pictures";
    private static final String CONTENT_URI = "content://us.mikeandwan.streamprovider/";
    private Context _context;


    public PhotoStorage(Context context) {
        _context = context;
    }


    public boolean put(String remotePath, HttpURLConnection conn) {
        File dir = new File(getRootPath(), remotePath.substring(0, remotePath.lastIndexOf('/')));
        File file = getCachePath(remotePath);
        OutputStream outputStream = null;

        dir.mkdirs();

        try {
            byte[] buffer = new byte[4096];
            int n;
            InputStream inputStream = conn.getInputStream();
            outputStream = new FileOutputStream(file);

            while ((n = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, n);
            }
        } catch (FileNotFoundException e) {
            Log.w(MawApplication.LOG_TAG, "Error saving image file: " + e.getMessage());
            return false;
        } catch (IOException e) {
            Log.w(MawApplication.LOG_TAG, "Error saving image file: " + e.getMessage());
            return false;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception ex) {
                    // swallow
                }
            }
        }

        return true;
    }


    public boolean doesExist(String remotePath) {
        File file = getCachePath(remotePath);

        return file.exists();
    }


    public Bitmap get(String remotePath) {
        File file = getCachePath(remotePath);

        if (!file.exists()) {
            return null;
        }

        return BitmapFactory.decodeFile(file.getAbsolutePath());
    }


    public Bitmap getPlaceholderThumbnail() {
        return Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
    }


    public File getCachePath(String remotePath) {
        return new File(getRootPath(), remotePath);
    }


    public Uri getSharingContentUri(String remotePath) {
        File file = new File(Environment.DIRECTORY_PICTURES, remotePath);

        return Uri.parse(CONTENT_URI + file.getPath());
    }


    private File getRootPath() {
        return _context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }


    public void wipeLegacyCache() {
        File dir = new File(getLegacyRootPath());

        try {
            FileUtils.deleteDirectory(dir);
        } catch (IOException ex) {
            Log.e(MawApplication.LOG_TAG, "Unable to delete legacy directory: " + ex.getMessage());
        }
    }


    private String getLegacyRootPath() {
        return String.valueOf(Environment.getExternalStorageDirectory()) + "/" + MAW_ROOT;
    }
}

@@ -258,36 +258,124 @@
 eUtils;%0A
-%0Aimport java.io.File
+import org.apache.commons.io.filefilter.DirectoryFileFilter;%0A%0Aimport java.io.File;%0Aimport java.io.FileFilter
 ;%0Aimport
@@ -3141,24 +3141,51 @@
 cyCache() %7B%0A
+        wipePriorCache();%0A%0A
         File
@@ -3450,127 +3450,1442 @@
 ate 
-String getLegacyRootPath() %7B%0A        return String.valueOf(Environment.getExternalStorageDirectory()) + %22/%22 + MAW_ROOT;
+void wipePriorCache() %7B%0A        // with latest site, the dir names are now different (xs, sm, lg, etc) rather than%0A        // (fullsize, fuller, orig, etc).  this kills the older cache as they will no longer%0A        // be referenced%0A        try %7B%0A            wipePrior(getRootPath());%0A        %7D catch (IOException ex) %7B%0A            Log.e(MawApplication.LOG_TAG, %22Unable to delete newer cache directory: %22 + ex.getMessage());%0A        %7D%0A    %7D%0A%0A%0A    private void wipePrior(File dir) throws IOException %7B%0A        if(dir == null) %7B%0A            return;%0A        %7D%0A%0A        if(isPrior(dir)) %7B%0A            FileUtils.deleteDirectory(dir);%0A            return;%0A        %7D%0A%0A        for(File subdir : dir.listFiles(new DirectoryFilter())) %7B%0A            wipePrior(subdir);%0A        %7D%0A    %7D%0A%0A%0A    private String getLegacyRootPath() %7B%0A        return String.valueOf(Environment.getExternalStorageDirectory()) + %22/%22 + MAW_ROOT;%0A    %7D%0A%0A%0A    private boolean isPrior(File dir) %7B%0A        if(dir.isDirectory()) %7B%0A            return %22thumbnails%22.equalsIgnoreCase(dir.getName()) %7C%7C%0A                    %22fuller%22.equalsIgnoreCase(dir.getName()) %7C%7C%0A                    %22fullsize%22.equalsIgnoreCase(dir.getName()) %7C%7C%0A                    %22orig%22.equalsIgnoreCase(dir.getName());%0A        %7D%0A%0A        return false;%0A    %7D%0A%0A%0A    private class DirectoryFilter implements FileFilter %7B%0A        public boolean accept(File file) %7B%0A            return file.isDirectory();%0A        %7D
 %0A   

delete the old images that were downloaded, as all images for the site have been re-processed, and also live in new directories