/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-atlasmap-plugin
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
var EntaxyAtlasmap;
(function (EntaxyAtlasmap) {
    EntaxyAtlasmap.log.debug("loading console");

    EntaxyAtlasmap._module
    .component('entaxyAtlasmapConsole', {
        template: `<iframe id="atlasmapConsoleFrame" src='/atlasmap-ui' class="entaxy-atlasmap-console"></iframe>`,
        controller: EntaxyAtlasmapConsoleController
    })
    .name;

    function EntaxyAtlasmapConsoleController($element, $uibModal, $scope, workspace, operationsService, $location) {
        'ngInject';
        let ctrl = this;
        let iframe = $element.context.childNodes[0];

        ctrl.$onInit = function () {
            let locationSearchObject = $location.search();
            if (locationSearchObject && locationSearchObject.location) {
                ctrl.admLocation = locationSearchObject.location;
                if (!isOpenedInModal()) {
                    hideNavigation();
                }
            }
        }

        window.onmessage = function (event) {
            if (event.origin !== iframe.contentWindow.origin) {
                return;
            }
            switch (event.data) {
                case 'openRegistryViewerForExport':
                    openViewer('*.adm', true, true, 'exportMapping');
                    break;
                case 'openRegistryViewerForImport':
                    openViewer('*.adm', false, false, 'importMapping');
                    break;
                case 'openRegistryViewerForImportInstanceOrSchemaFile':
                    openViewer(['*.json', '*.xml', '*.xsd', '*.csv'], false, false, 'importInstanceOrSchema');
                    break;
                case 'openCreateInstanceOrSchemaModal':
                    openCreateInstanceOrSchemaModal();
                    break;
                case 'readyForInitData':
                    sendInitData();
                    break;
            }
        }

        function sendInitData() {
            let locationSearchObject = $location.search();
            let message = {
                type: 'init',
                hideImport: locationSearchObject && locationSearchObject.location,
                hideExport: locationSearchObject && locationSearchObject.location && isOpenedInModal(),
                waitForSaving: locationSearchObject && locationSearchObject.location && isOpenedInModal()
            }
            iframe.contentWindow.postMessage(message, iframe.contentWindow.origin);
        }

        function isOpenedInModal() {
            return iframe.parentElement && iframe.parentElement.parentElement &&
                iframe.parentElement.parentElement.classList.contains('entaxy-atlasmap-console-container');
        }

        function openViewer(filter, folderSelectionEnabled, folderAddingEnabled, type) {

            let config = {
                resourceProvider: 'schemas',
                filter: filter,
                useShortUrl: true,
                folderSelectionEnabled: folderSelectionEnabled,
                folderAddingEnabled: folderAddingEnabled,
                saveMode: type === 'exportMapping'
            };

            const admOperation = type.match('Mapping');

            $uibModal.open({
                component: 'entaxyResourceViewerModal',
                resolve: {
                    location: () => admOperation ? ctrl.admLocation : ctrl.instanceLocation,
                    config: () => config
                },
                size: 'xl',
                backdrop: 'static'
            }).result.then(location => {
                if (admOperation) {
                    ctrl.admLocation = location;
                } else {
                    ctrl.instanceLocation = location;
                }
                let message = {
                    type: type,
                    content: location
                }
                iframe.contentWindow.postMessage(message, iframe.contentWindow.origin);
            });
        }

        function openCreateInstanceOrSchemaModal() {
            $uibModal.open({
                component: 'entaxyCreateResourceModal',
                resolve: {
                    modalTitle: () => 'Create an instance or schema',
                    resourceName: () => 'userContent'
                },
                size: 'xl',
                backdrop: 'static'
            })
            .result.then(content => {
                let message = {
                    type: 'createInstanceOrSchema',
                    content: content
                };
                iframe.contentWindow.postMessage(message, iframe.contentWindow.origin);
            });
        }

        function hideNavigation() {
            let sidebar = document.getElementsByClassName('pf-c-page__sidebar')[0];
            sidebar.classList.replace('pf-m-expanded', 'pf-m-collapsed');
            let menuButton = document.getElementsByClassName('pf-c-page__header-brand-toggle')[0];
            menuButton.style.display = 'none';
        }

    }
    EntaxyAtlasmapConsoleController.$inject = ['$element', '$uibModal', '$scope', 'workspace', 'operationsService',
        '$location']

})(EntaxyAtlasmap || (EntaxyAtlasmap = {}));
