/*
   Copyright 2024 Total Pave Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.totalpave.cordova.sentry;

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

public class Sentry extends CordovaPlugin {

    @Override
    protected void pluginInitialize() {
        io.sentry.SentryOptions options = io.sentry.Sentry.getCurrentScopes().getOptions();

        String debugID = preferences.getString("SENTRY_DEBUG_ID", "not-set");
        if (debugID != null && !debugID.equals("not-set")) {
            options.addBundleId(debugID);
        }

        boolean sentryDebugMode = preferences.getBoolean("SENTRY_DEBUG", false);
        options.setDebug(sentryDebugMode);

        String sentryEnvironment = preferences.getString("SENTRY_ENVIRONMENT", "production");
        options.setEnvironment(sentryEnvironment);

        String sentryRelease = preferences.getString("SENTRY_RELEASE", null);
        if (sentryRelease != null) {
            options.setRelease(sentryRelease);
        }

        String sentryDist = preferences.getString("SENTRY_DIST", null);
        if (sentryDist != null) {
            options.setRelease(sentryDist);
        }
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callback) {
        if (action.equals("testNativeException")) {
            this.$testNativeException();
            return true;
        }

        return false;
    }

    private void $testNativeException() {
        RuntimeException ex = new RuntimeException("Test Native Exception");
        io.sentry.Sentry.captureException(ex);
    }
}
