/**
 * @copyright (c) Microsoft Corporation. All rights reserved.
 */
'use strict';

const componentName = "Microsoft.Pay.startup.js";
const walletHost = "wallet.microsoft.com";
const walletPath = '/preview/';
const osVersionParam = 'os';
const appVersionParam = 'app';
const launchArguments = 'launchArgs';

function processException(message, error) {
    error = error || {};
    const safeError = {
        name: error.name || null,
        message: error.message || null,
        stack: error.stack || null,
        number: error.number || null
    };
    
    const errorMessage = `${message}, Exception: ${JSON.stringify(safeError)}`;
    Microsoft.Pay.Background.Telemetry.TelemetryEvent.unhandledException(componentName, errorMessage, safeError.number);
}

try {
    Microsoft.Pay.Background.Telemetry.TelemetryEvent.applicationLaunched(componentName);

    // Extract transaction ID from the app launch args.
    Windows.UI.WebUI.WebUIApplication.onactivated = function (eventArgs) {
        try {
            const appPackage = Windows.ApplicationModel.Package.current;
            const packageVersionInfo = appPackage.id.version;
            const appVersion = `${packageVersionInfo.major}.${packageVersionInfo.minor}.${packageVersionInfo.revision}`;
            const osVersion = Microsoft.Pay.Background.Telemetry.TelemetryDataProvider.currentOSVersion;

            const url = (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.protocol) ?
                new URL(eventArgs.uri.absoluteUri) : new URL(`https://${walletHost}${walletPath}`);
            url.searchParams.set(osVersionParam, osVersion);
            url.searchParams.set(appVersionParam, appVersion);

            if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                url.searchParams.set(launchArguments, eventArgs.arguments);
            }

            Microsoft.Pay.Background.Telemetry.TelemetryEvent.applicationActivated(componentName, eventArgs.kind, eventArgs.arguments, url.host);
            window.location.href = url.href;
        }
        catch (e) {
            processException('An activation error occurred.', e);
        }
    };
}
catch (e) {
    processException('An error occurred while processing the startup.js file.', e);
}
