/**
 * 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) {

    // infer mime type from uri
    String mimeType = HttpURLConnection.guessContentTypeFromName(path);

    // if mime guess fails, do legwork
    if (mimeType == null) {
      String extension = MimeTypeMap.getFileExtensionFromUrl(path);
      if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        mimeType = mime.getMimeTypeFromExtension(extension);
      }
    }

    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);
    }
  }
}

@@ -1277,16 +1277,63 @@
 ing(0);%0A
+      if (path != null && path.length() %3E 0) %7B%0A
         
@@ -1398,22 +1398,16 @@
 ;%0A      
-%7D%0A    
   return
@@ -1412,16 +1412,100 @@
 rn true;
+%0A      %7D else %7B%0A        return false;%0A      %7D%0A    %7D else %7B%0A      return false;%0A    %7D
 %0A  %7D%0A%0A  
@@ -2259,55 +2259,8 @@
 ) %7B%0A
-    if (path != null && path.length() %3E 0) %7B%0A  
     
@@ -2267,26 +2267,24 @@
 try %7B%0A      
- 
- 
 Uri uri = Ur
@@ -2294,26 +2294,24 @@
 arse(path);%0A
-  
       String
@@ -2343,18 +2343,16 @@
 ;%0A      
- 
- 
 Intent i
@@ -2391,18 +2391,16 @@
 _VIEW);%0A
-  
       Co
@@ -2469,18 +2469,16 @@
 %0A%0A      
- 
- 
 // TODO 
@@ -2533,18 +2533,16 @@
 wnload,%0A
-  
       //
@@ -2609,18 +2609,16 @@
 s%0A      
- 
- 
 // becau
@@ -2682,18 +2682,16 @@
 e%0A      
-  
 // the m
@@ -2743,18 +2743,16 @@
 e%0A      
- 
- 
 intent.s
@@ -2795,18 +2795,16 @@
 ;%0A      
-  
 context.
@@ -2829,26 +2829,24 @@
 nt);%0A%0A      
- 
- 
 callbackCont
@@ -2856,26 +2856,24 @@
 .success();%0A
-  
     %7D catch 
@@ -2906,26 +2906,24 @@
  e) %7B%0A      
- 
- 
 e.printStack
@@ -2927,26 +2927,24 @@
 ackTrace();%0A
-  
       callba
@@ -2980,61 +2980,8 @@
 ));%0A
-      %7D%0A    %7D else %7B%0A      callbackContext.error(2);%0A
     

Check for valid args earlier in logic