package com.verso.cordova.clipboard;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.ClipDescription;

public class Clipboard extends CordovaPlugin {

    private static final String ACTION_COPY = "copy";
    private static final String ACTION_PASTE = "paste";

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        ClipboardManager clipboard = (ClipboardManager) cordova.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);

        if (ACTION_COPY.equals(action)) {
            try {
                String text = args.getString(0);
                ClipData clip = ClipData.newPlainText("Text", text);

                clipboard.setPrimaryClip(clip);

                callbackContext.success(text);

                return true;
            } catch (JSONException e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Exception e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.toString()));
            }
        } else if (ACTION_PASTE.equals(action)) {
            try {
                ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
                String text = item.getText().toString();

                if (text == null) text = "";

                callbackContext.success(text);

                return true;
            } catch (Exception e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.toString()));
            }
        }
        return false;
    }
}

@@ -841,32 +841,38 @@
                 
+final 
 String text = ar
@@ -884,24 +884,24 @@
 tString(0);%0A
-
             
@@ -953,25 +953,24 @@
 xt%22, text);%0A
-%0A
             
@@ -1045,33 +1045,32 @@
 .success(text);%0A
-%0A
                 
@@ -1445,32 +1445,66 @@
           try %7B%0A
+                String text = %22%22;%0A
                 
@@ -1515,18 +1515,13 @@
 Data
-.Item item
+ clip
  = c
@@ -1545,16 +1545,99 @@
 ryClip()
+;%0A                if (clip != null) %7B%0A                    ClipData.Item item = clip
 .getItem
@@ -1651,38 +1651,35 @@
                 
-String
+   
  text = item.get
@@ -1697,17 +1697,16 @@
 ring();%0A
-%0A
         
@@ -1717,37 +1717,9 @@
     
-if (text == null) text = %22%22;%0A
+%7D
 %0A   
@@ -1762,17 +1762,16 @@
 (text);%0A
-%0A
         

Fix null pointer exception in paste method (#2)