package org.wikipedia.gallery;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import org.wikipedia.R;
import org.wikipedia.feed.image.FeaturedImage;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.FileUtil;

public class MediaDownloadReceiver extends BroadcastReceiver {
    private static final String FILE_NAMESPACE = "File:";

    @NonNull private Activity activity;
    @NonNull private DownloadManager downloadManager;

    public MediaDownloadReceiver(@NonNull Activity activity) {
        this.activity = activity;
        downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
    }

    public void download(@NonNull FeaturedImage featuredImage) {
        String filename = FileUtil.sanitizeFileName(featuredImage.title());
        String targetDirectory = Environment.DIRECTORY_PICTURES;
        performDownloadRequest(featuredImage.image().source(), targetDirectory, filename, null);
    }

    public void download(@NonNull GalleryItem galleryItem) {
        String saveFilename = FileUtil.sanitizeFileName(trimFileNamespace(galleryItem.getName()));
        String targetDirectory;
        if (FileUtil.isVideo(galleryItem.getMimeType())) {
            targetDirectory = Environment.DIRECTORY_MOVIES;
        } else if (FileUtil.isAudio(galleryItem.getMimeType())) {
            targetDirectory = Environment.DIRECTORY_MUSIC;
        } else if (FileUtil.isImage(galleryItem.getMimeType())) {
            targetDirectory = Environment.DIRECTORY_PICTURES;
        } else {
            targetDirectory = Environment.DIRECTORY_DOWNLOADS;
        }
        performDownloadRequest(Uri.parse(galleryItem.getUrl()), targetDirectory, saveFilename,
                galleryItem.getMimeType());
    }

    private void performDownloadRequest(@NonNull Uri uri, @NonNull String targetDirectory,
                                        @NonNull String filename, @Nullable String mimeType) {
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationInExternalFilesDir(activity, targetDirectory, filename);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        if (mimeType != null) {
            request.setMimeType(mimeType);
        }
        request.allowScanningByMediaScanner();

        downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadManager.enqueue(request);
        FeedbackUtil.showMessage(activity, R.string.gallery_save_progress);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            Cursor c = downloadManager.query(query);
            try {
                if (c.moveToFirst()) {
                    int statusIndex = c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
                    int pathIndex = c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI);
                    int mimeIndex = c.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(statusIndex)) {
                        FeedbackUtil.showMessage(activity, R.string.gallery_save_success);
                        notifyContentResolver(Uri.parse(c.getString(pathIndex)).getPath(),
                                c.getString(mimeIndex));
                    }
                }
            } finally {
                c.close();
            }
        }
    }

    @NonNull private String trimFileNamespace(@NonNull String filename) {
        return filename.startsWith(FILE_NAMESPACE) ? filename.substring(FILE_NAMESPACE.length()) : filename;
    }

    private void notifyContentResolver(@NonNull String path, @NonNull String mimeType) {
        ContentValues values = new ContentValues();
        Uri contentUri;
        if (FileUtil.isVideo(mimeType)) {
            values.put(MediaStore.Video.Media.DATA, path);
            values.put(MediaStore.Video.Media.MIME_TYPE, mimeType);
            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if (FileUtil.isAudio(mimeType)) {
            values.put(MediaStore.Audio.Media.DATA, path);
            values.put(MediaStore.Audio.Media.MIME_TYPE, mimeType);
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        } else {
            values.put(MediaStore.Images.Media.DATA, path);
            values.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        }
        activity.getContentResolver().insert(contentUri, values);
    }
}

@@ -468,16 +468,51 @@
 edia.R;%0A
+import org.wikipedia.WikipediaApp;%0A
 import o
@@ -627,16 +627,38 @@
 eUtil;%0A%0A
+import java.io.File;%0A%0A
 public c
@@ -1147,21 +1147,27 @@
  String 
-filen
+targetFileN
 ame = Fi
@@ -1236,32 +1236,36 @@
  targetDirectory
+Type
  = Environment.D
@@ -1361,23 +1361,33 @@
 irectory
-, filen
+Type, targetFileN
 ame, nul
@@ -1587,16 +1587,20 @@
 irectory
+Type
 ;%0A      
@@ -1671,32 +1671,36 @@
  targetDirectory
+Type
  = Environment.D
@@ -1801,32 +1801,36 @@
  targetDirectory
+Type
  = Environment.D
@@ -1930,32 +1930,36 @@
  targetDirectory
+Type
  = Environment.D
@@ -2021,16 +2021,20 @@
 irectory
+Type
  = Envir
@@ -2150,16 +2150,20 @@
 irectory
+Type
 , saveFi
@@ -2310,16 +2310,20 @@
 irectory
+Type
 ,%0A      
@@ -2372,21 +2372,27 @@
  String 
-filen
+targetFileN
 ame, @Nu
@@ -2409,32 +2409,493 @@
 ing mimeType) %7B%0A
+        final String targetSubfolderName = WikipediaApp.getInstance().getString(R.string.app_name);%0A        final File categoryFolder = Environment.getExternalStoragePublicDirectory(targetDirectoryType);%0A        final File targetFolder = new File(categoryFolder, targetSubfolderName);%0A        final File targetFile = new File(targetFolder, targetFileName);%0A%0A        // creates the directory if it doesn't exist else it's harmless%0A        targetFolder.mkdir();%0A%0A
         Download
@@ -2988,62 +2988,36 @@
 tion
-InExternalFilesDir(activity, targetDirectory, filename
+Uri(Uri.fromFile(targetFile)
 );%0A 

Change the download location of files