(function (w) {
    'use strict';
    const icons = 'c4it-f4sd-icons';
    w.mx = w.mx || {};
    w.mx.workspacesConfig = w.mx.workspacesConfig || {};
    w.mx.workspacesConfig.modules = w.mx.workspacesConfig.modules || {};
    w.mx.workspacesConfig.modules.add = w.mx.workspacesConfig.modules.add || function (name, config) {
        w.mx.workspacesConfig.modules[name] = config;
    };

    w.mx.workspacesConfig.modules.add('mx.C4IT.F4SD', {
        name: 'mx.C4IT.F4SD',
        config: ['$mdIconProvider', function ($mdIconProvider) {
            $mdIconProvider.iconSet(icons, 'workspaces/C4IT_F4SD/F4SDIcons.svg');

            w.mx.components = w.mx.components || {};
            w.mx.components.Icons = w.mx.components.Icons || [];

            w.mx.components.Icons.unshift({
                id: icons,
                name: 'C4IT F4SD Icons',
                icons: [{
                    SVG: true,
                    id: `${icons}:icon-f4sd`,
                    name: 'F4SD Icon',
                    keywords: ['c4it', 'custom', 'f4sd']
                }, {
                    SVG: true,
                    id: `${icons}:icon-f4sd-coloured`,
                    name: 'F4SD Icon (coloured)',
                    keywords: ['c4it', 'custom', 'f4sd']
                }]
            });
        }]
    });
})(window);

(function (w) {
    'use strict';

    angular.module("mx.C4IT.F4SD")
        .controller("mx.C4IT.F4SD.Actions.callF4SD", [
            "mx.shell.Config",
            "mx.SolutionBuilderAgent.Http",
            "mx.shell.NotificationService",
            "mx.internationalization",
            function (shellConfig, $http, notificationService, i18n) {
                const vm = this;
                const F4SD_URL_PREFIX = 'f4sdsend://localhost/';
                const ERROR_INVALID_RESPONSE = "Invalid response from server";
                const ERROR_SERVICE_UNAVAILABLE = "Service not available";

                vm.restHost = shellConfig.settings.restHosts.default;
                vm.messageF4SDOpened = i18n.get('c4it.f4sd.action-open-called') || 'F4SD wird geöffnet...';

                vm.execute = function (conf, para) {
                    const eoid = conf[0]['Sys-ObjectId'] || conf[0].ID;

                    // Aktionsparameter abrufen
                    if (para.controllerParams) {
                        try {
                            vm.controllerParams = new URLSearchParams(para.controllerParams);
                        } catch (error) {
                            console.error('Fehler beim Parsen der Controller-Parameter:', error);
                            notificationService.error("Formatfehler in Aktionskonfigurationsparametern");
                            return;
                        }
                    } else {
                        vm.controllerParams = new URLSearchParams();
                    }

                    // F4SD-URL abrufen
                    const uri = new URL("api/c4itf4sdwebapi/getdirectlinkf4sd/", vm.restHost);
                    uri.searchParams.append("type", vm.controllerParams.get("type") || para.name);
                    uri.searchParams.append("eoid", eoid);

                    $http.get(uri.pathname + uri.search).then((response) => {
                        try {
                            const n = response.data || response;

                            if (typeof n !== 'string') {
                                console.error('Unerwartetes Datenformat:', n);
                                notificationService.error(ERROR_INVALID_RESPONSE);
                                return;
                            }

                            if (!n.startsWith(F4SD_URL_PREFIX)) {
                                notificationService.error(ERROR_SERVICE_UNAVAILABLE);
                                return;
                            }

                            if (vm.controllerParams.get("showNotification") === '1') {
                                notificationService.info(vm.messageF4SDOpened);
                            }
                            window.location.href = n;

                        } catch (error) {
                            console.error(`Fehler beim Verarbeiten der Antwort-URL: ${error}`);
                            notificationService.error(ERROR_SERVICE_UNAVAILABLE);
                        }
                    }).catch((error) => {
                        console.error('HTTP-Anfrage fehlgeschlagen:', error);
                        notificationService.error(ERROR_SERVICE_UNAVAILABLE);
                    });
                };
            }
        ]);
})(window);
