package cordova.plugin.bubbles;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;
import android.content.res.Resources;
import android.app.Application;
import android.net.Uri;
import android.content.IntentFilter;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.content.SharedPreferences;
/**
 * This class echoes a string called from JavaScript.
 */
public class bubblesPlugin extends CordovaPlugin {
    private bubbleBroadcastReceiver receiver;
    private static final int DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODE = 1222;
    public CallbackContext callbackContext = null;
    public JSONObject params = null;
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("createFloatingBubbles")) {
            params = new JSONObject(args.get(0).toString());
            this.callbackContext = callbackContext;
            createFloatingBubbles(getView(), params, callbackContext);

            // Don't return any result now, since status results will be sent when events come in from broadcast receiver
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);

            return true;
        }else if(action.equals("removeFloatingBubbles")){
            this.destroy(callbackContext);  
            return true;
        }
        return false;
    }

    /*  start floating widget service  */
    public void createFloatingBubbles(View view, JSONObject params, CallbackContext callbackContext) {
        //Check if the application has draw over other apps permission or not?
        //This permission is by default available for API<23. But for API > 23
        //you have to ask for the permission in runtime.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(cordova.getActivity())) {
            //If the draw over permission is not available open the settings screen
            //to grant the permission.
            cordova.setActivityResultCallback((CordovaPlugin) this);
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + cordova.getActivity().getApplication().getPackageName()));
            cordova.startActivityForResult((CordovaPlugin) this, intent, DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODE);

        } else{
            //If permission is granted start floating widget service
            startFloatingWidgetService(params, callbackContext);
        }
     
    }

    /*  Start Floating widget service and finish current activity */
    private void startFloatingWidgetService(JSONObject params, CallbackContext callbackContext) {
        try {
            receiver = new bubbleBroadcastReceiver(callbackContext);                    
            IntentFilter filter = new IntentFilter();
            filter.addAction("onCallanswered");
            filter.addAction("onCalldeclined");
            getView().getContext().registerReceiver(receiver, filter);
            FloatingWidgetService.isServiceRunning = true;
            Intent intent = new Intent(cordova.getActivity(), FloatingWidgetService.class);
            SharedPreferences settings = this.cordova.getActivity().getSharedPreferences("BUBBULES_SHARED", 0);
            SharedPreferences.Editor editor = settings.edit();
                editor.putInt("count", params.getInt("badge"));
                editor.putString("widget_label",params.getString("widget_label"));
                editor.putString("widget_details",params.getString("widget_details"));
                editor.putString("type",params.getString("type"));
                editor.apply();
            Context context = this.cordova.getActivity().getApplicationContext();
            context.startService(intent);
        }catch (java.lang.Exception e){
            FloatingWidgetService.isServiceRunning = false;
            callbackContext.error(e.getMessage());
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODE) {
            //Check if the permission is granted or not.
            if (resultCode == Activity.RESULT_OK)
                //If permission granted start floating widget service
                startFloatingWidgetService(this.params, this.callbackContext);
            else{
                //Permission is not available then display toast
                Log.d("onActivityResult", "Permission is not available");
                callbackContext.error("Permission is not available");
            }

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void destroy(final CallbackContext callbackContext) {
        if(FloatingWidgetService.isServiceRunning){
            Intent intent = new Intent(cordova.getActivity(), FloatingWidgetService.class);
            Context context = this.cordova.getActivity().getApplicationContext();
            context.stopService(intent);
            callbackContext.success("FloatingBubbles removed");
        }else{
            callbackContext.error("FloatingBubbles is not yet initialized");
        }
    }

     private View getView() {
        try {
            return (View) webView.getClass().getMethod("getView").invoke(webView);
        } catch (Exception e) {
            return (View) webView;
        }
    }
}
