/**
 * 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();

        // TODO normalize is used because the uri is from the download,
        // which is a temporary file and ends in .tmp. The method works
        // because we use mime based on our own method. We could deprecate
        // the mime method by downloading to permanent storage
        intent.setDataAndTypeAndNormalize(uri, mime);
        context.startActivity(intent);

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

  private File downloadFile(String url, CallbackContext callbackContext) {
    try {
      Uri uri  = Uri.parse(url);
      String Filename = uri.getLastPathSegment();

      CookieManager cookieManager = CookieManager.getInstance();
      String cookie = null;
      if (cookieManager.getCookie(url) != null) {
        cookie = cookieManager.getCookie(url).toString();
      }

      URL tempUrl = new URL(url);
      HttpURLConnection connection = (HttpURLConnection) tempUrl.openConnection();
      if (cookie != null) {
        connection.setRequestProperty("Cookie", cookie);
      }

      Context context = cordova.getActivity().getApplicationContext();
      InputStream inputStream = connection.getInputStream();
      String ext = MimeTypeMap.getFileExtensionFromUrl(url);
      File file = File.createTempFile(Filename, "." + ext, context.getExternalCacheDir());

      file.setReadable(true, false);
      OutputStream outputStream = new FileOutputStream(file);

      byte[] data = new byte[1024];
      int buffer = 0;

      while ((buffer = inputStream.read(data)) > 0) {
        outputStream.write(data, 0, buffer);
        outputStream.flush();
      }

      outputStream.close();
      inputStream.close();

      return file;
    } catch(IOException e) {
      e.printStackTrace();
      callbackContext.error(e.getMessage());
    }
    return null;
  }

  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, callbackContext);
      return file;
    }

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

@@ -1519,41 +1519,187 @@
 ) %7B%0A
-    String mimeType = null;%0A%0A
+%0A    // infer mime type from uri%0A    String mimeType = HttpURLConnection.guessContentTypeFromName(path);%0A%0A    // if mime guess fails, do legwork%0A    if (mimeType == null) %7B%0A 
     
+ 
 Stri
@@ -1752,24 +1752,26 @@
 mUrl(path);%0A
+  
     if (exte
@@ -1793,16 +1793,18 @@
 %7B%0A      
+  
 MimeType
@@ -1848,16 +1848,18 @@
 ;%0A      
+ 
+ 
 mimeType
@@ -1911,60 +1911,17 @@
     
+  
 %7D
-%0A
 %0A    
-System.out.println(%22Mime type: %22 + mimeType);
+%7D
 %0A%0A  

Use built in mime type method