package br.com.FBRegistroPro;

import android.app.Activity;
import android.content.Context;
import android.view.WindowManager;

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

public class ScreenCapturePlugin extends CordovaPlugin {
    static final String PREFS_NAME = "registropro_screen_capture";
    static final String PREFS_KEY_ALLOWED = "allowed";

    public static void applySavedPolicy(Activity activity) {
        if (activity == null) {
            return;
        }
        boolean allowed = activity.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                .getBoolean(PREFS_KEY_ALLOWED, false);
        applyPolicy(activity, allowed);
    }

    static void applyPolicy(Activity activity, boolean allowed) {
        if (activity == null) {
            return;
        }
        if (allowed) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
        } else {
            activity.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_SECURE,
                    WindowManager.LayoutParams.FLAG_SECURE);
        }
    }

    static void persistPolicy(Context context, boolean allowed) {
        if (context == null) {
            return;
        }
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                .edit()
                .putBoolean(PREFS_KEY_ALLOWED, allowed)
                .apply();
    }

    @Override
    public void pluginInitialize() {
        super.pluginInitialize();
        applySavedPolicy(cordova.getActivity());
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (!"setAllowed".equals(action)) {
            return false;
        }
        final boolean allowed = args.length() > 0 && args.getBoolean(0);
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                persistPolicy(cordova.getContext(), allowed);
                applyPolicy(cordova.getActivity(), allowed);
                callbackContext.success();
            }
        });
        return true;
    }
}
