package br.com.trimsy.notify;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;

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

public class TrimsyNotify extends CordovaPlugin {
    private static final int REQ_POST = 7917;
    private CallbackContext pendingPerm;

    @Override
    protected void pluginInitialize() {
        try {
            NotifyHub.ensureChannel(cordova.getActivity());
            handleLaunchIntent(cordova.getActivity().getIntent());
        } catch (Exception ignored) {}
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleLaunchIntent(intent);
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
        try {
            if ("requestPermission".equals(action)) {
                requestPermission(callbackContext);
                return true;
            }
            if ("hasPermission".equals(action)) {
                callbackContext.success(NotifyHub.notificationsAllowed(cordova.getActivity()) ? 1 : 0);
                return true;
            }
            if ("show".equals(action)) {
                JSONObject opts = args.optJSONObject(0);
                if (opts == null) opts = new JSONObject();
                final JSONObject item = normalize(opts, false);
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        NotifyHub.show(
                            cordova.getActivity().getApplicationContext(),
                            item.optInt(NotifyHub.EXTRA_ID, 1),
                            item.optString(NotifyHub.EXTRA_TITLE),
                            item.optString(NotifyHub.EXTRA_BODY),
                            item.optString(NotifyHub.EXTRA_PAYLOAD)
                        );
                    }
                });
                callbackContext.success();
                return true;
            }
            if ("schedule".equals(action)) {
                JSONObject opts = args.optJSONObject(0);
                if (opts == null) opts = new JSONObject();
                final JSONObject item = normalize(opts, true);
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        NotifyHub.schedule(cordova.getActivity().getApplicationContext(), item);
                    }
                });
                callbackContext.success();
                return true;
            }
            if ("cancel".equals(action)) {
                final int id = args.optInt(0, 0);
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        NotifyHub.cancel(cordova.getActivity().getApplicationContext(), id);
                    }
                });
                callbackContext.success();
                return true;
            }
            if ("cancelAll".equals(action)) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        NotifyHub.cancelAll(cordova.getActivity().getApplicationContext());
                    }
                });
                callbackContext.success();
                return true;
            }
            if ("openSettings".equals(action)) {
                openSettings();
                callbackContext.success();
                return true;
            }
            if ("getToken".equals(action)) {
                getFcmToken(callbackContext);
                return true;
            }
        } catch (Exception e) {
            callbackContext.error(e.getMessage() != null ? e.getMessage() : "notify_failed");
            return true;
        }
        return false;
    }

    private void getFcmToken(final CallbackContext cb) {
        try {
            com.google.firebase.messaging.FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new com.google.android.gms.tasks.OnCompleteListener<String>() {
                    public void onComplete(com.google.android.gms.tasks.Task<String> task) {
                        if (!task.isSuccessful() || task.getResult() == null || task.getResult().length() == 0) {
                            cb.error("fcm_token_failed");
                            return;
                        }
                        String token = task.getResult();
                        try {
                            cordova.getActivity().getSharedPreferences(NotifyHub.PREFS, android.content.Context.MODE_PRIVATE)
                                .edit()
                                .putString("fcm_token", token)
                                .apply();
                        } catch (Exception ignored) {}
                        cb.success(token);
                    }
                });
        } catch (Exception e) {
            cb.error(e.getMessage() != null ? e.getMessage() : "fcm_unavailable");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode != REQ_POST || pendingPerm == null) return;
        CallbackContext cb = pendingPerm;
        pendingPerm = null;
        boolean ok = grantResults != null && grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED;
        cb.success(ok ? 1 : 0);
    }

    private void requestPermission(CallbackContext cb) {
        if (Build.VERSION.SDK_INT < 33 || NotifyHub.notificationsAllowed(cordova.getActivity())) {
            cb.success(1);
            return;
        }
        pendingPerm = cb;
        cordova.requestPermission(this, REQ_POST, Manifest.permission.POST_NOTIFICATIONS);
    }

    private void openSettings() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, cordova.getActivity().getPackageName());
        } else {
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(android.net.Uri.parse("package:" + cordova.getActivity().getPackageName()));
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        cordova.getActivity().startActivity(intent);
    }

    private JSONObject normalize(JSONObject opts, boolean schedule) throws Exception {
        JSONObject item = new JSONObject();
        int id = opts.optInt("id", 0);
        if (id == 0) id = Math.abs(String.valueOf(opts.optString("key", String.valueOf(System.currentTimeMillis()))).hashCode());
        if (id == 0) id = 1;
        item.put(NotifyHub.EXTRA_ID, id);
        item.put(NotifyHub.EXTRA_TITLE, opts.optString("title", "Trimsy One"));
        item.put(NotifyHub.EXTRA_BODY, opts.optString("body", ""));
        Object extra = opts.opt("extra");
        if (extra instanceof JSONObject) item.put(NotifyHub.EXTRA_PAYLOAD, extra.toString());
        else item.put(NotifyHub.EXTRA_PAYLOAD, opts.optString("payload", opts.optString("extra", "")));
        if (schedule) item.put(NotifyHub.EXTRA_AT, opts.optLong("at", 0));
        return item;
    }

    private void handleLaunchIntent(Intent intent) {
        if (intent == null) return;
        String payload = intent.getStringExtra(NotifyHub.LAUNCH_PAYLOAD);
        if (payload == null || payload.length() == 0) return;
        intent.removeExtra(NotifyHub.LAUNCH_PAYLOAD);
        fireClick(payload);
    }

    private void fireClick(final String payload) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                try {
                    JSONObject data;
                    try {
                        data = new JSONObject(payload);
                    } catch (Exception e) {
                        data = new JSONObject();
                        data.put("payload", payload);
                    }
                    String js = "try{cordova.fireDocumentEvent('trimsy-notify'," + data.toString() + ");}catch(e){}";
                    if (webView.getEngine() != null) {
                        webView.getEngine().evaluateJavascript(js, null);
                    } else {
                        webView.loadUrl("javascript:" + js);
                    }
                } catch (Exception ignored) {}
            }
        });
    }
}
