/**
 * Open.java
 *
 * Copyright (C) 2014 Carlos Antonio
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 */

package com.bridge;

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

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;

import android.net.Uri;
import android.webkit.MimeTypeMap;
import android.webkit.CookieManager;
import android.content.Context;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.os.AsyncTask;

/**
 * This class starts an activity for an intent to view files
 */
public class Open extends CordovaPlugin {

  public static final String OPEN_ACTION = "open";

  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals(OPEN_ACTION)) {
      String path = args.getString(0);
        new FileDownloadAsyncTask(path, callbackContext).execute();
      }
      return true;
  }

  /**
   * Returns the MIME type of the file.
   *
   * @param path
   * @return
   */
  private static String getMimeType(String path) {
    String mimeType = null;

    String extension = MimeTypeMap.getFileExtensionFromUrl(path);
    if (extension != null) {
      MimeTypeMap mime = MimeTypeMap.getSingleton();
      mimeType = mime.getMimeTypeFromExtension(extension);
    }

    System.out.println("Mime type: " + mimeType);

    return mimeType;
  }

  /**
   * Creates an intent for the data of mime type
   *
   * @param path
   * @param callbackContext
   */
  private void previewFile(String path, CallbackContext callbackContext) {
    if (path != null && path.length() > 0) {
      try {
        Uri uri = Uri.parse(path);
        String mime = getMimeType(path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Context context = cordova.getActivity().getApplicationContext();

        intent.setDataAndTypeAndNormalize(uri, mime);
        context.startActivity(intent);

        callbackContext.success();
      } catch (ActivityNotFoundException e) {
        e.printStackTrace();
        callbackContext.error(e.getMessage());
      }
    } else {
      callbackContext.error(2);
    }
  }

  private class FileDownloadAsyncTask extends AsyncTask<Void, Void, File> {
    private final CallbackContext callbackContext;
    private final String url;

    public FileDownloadAsyncTask(String url, CallbackContext callbackContext) {
      super();
      this.callbackContext = callbackContext;
      this.url = url;
    }

    @Override
    protected File doInBackground(Void... arg0) {
      // File file = downloadFile(url);
      return file;
    }

    @Override
    protected void onPostExecute(File result) {
      String path = result.toString();
      previewFile(path, callbackContext);
    }
  }
}

@@ -2280,24 +2280,306 @@
 Context();%0A%0A
+        // TODO normalize is used because the uri is from the download,%0A        // which is a temporary file and ends in .tmp. The method works%0A        // because we use mime based on our own method. We could deprecate%0A        // the mime method by downloading to permanent storage%0A
         inte
@@ -2881,16 +2881,1392 @@
  %7D%0A  %7D%0A%0A
+  private File downloadFile(String url, CallbackContext callbackContext) %7B%0A    try %7B%0A      Uri uri  = Uri.parse(url);%0A      String Filename = uri.getLastPathSegment();%0A%0A      CookieManager cookieManager = CookieManager.getInstance();%0A      String cookie = null;%0A      if (cookieManager.getCookie(url) != null) %7B%0A        cookie = cookieManager.getCookie(url).toString();%0A      %7D%0A%0A      URL tempUrl = new URL(url);%0A      HttpURLConnection connection = (HttpURLConnection) tempUrl.openConnection();%0A      if (cookie != null) %7B%0A        connection.setRequestProperty(%22Cookie%22, cookie);%0A      %7D%0A%0A      Context context = cordova.getActivity().getApplicationContext();%0A      InputStream inputStream = connection.getInputStream();%0A      String ext = MimeTypeMap.getFileExtensionFromUrl(url);%0A      File file = File.createTempFile(Filename, %22.%22 + ext, context.getExternalCacheDir());%0A%0A      file.setReadable(true, false);%0A      OutputStream outputStream = new FileOutputStream(file);%0A%0A      byte%5B%5D data = new byte%5B1024%5D;%0A      int buffer = 0;%0A%0A      while ((buffer = inputStream.read(data)) %3E 0) %7B%0A        outputStream.write(data, 0, buffer);%0A        outputStream.flush();%0A      %7D%0A%0A      outputStream.close();%0A      inputStream.close();%0A%0A      return file;%0A    %7D catch(IOException e) %7B%0A      e.printStackTrace();%0A      callbackContext.error(e.getMessage());%0A    %7D%0A    return null;%0A  %7D%0A%0A
   privat
@@ -4654,19 +4654,16 @@
  %7B%0A     
- //
  File fi
@@ -4679,24 +4679,41 @@
 loadFile(url
+, callbackContext
 );%0A      ret

Add file download method