/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-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 Entaxy;
(function (Entaxy) {

    const MODAL_MODES = {
        VIEW: 'View',
        EDIT: 'Edit',
        ADD: 'Add'
    };
    Entaxy.MODAL_MODES = MODAL_MODES;

    const RUNTIME_TYPE_PREFIX = 'entaxy.runtime.';
    Entaxy.RUNTIME_TYPE_PREFIX = RUNTIME_TYPE_PREFIX;
    const RUNTIME_TYPE_SECURITY_PREFIX = 'entaxy.security.';
    Entaxy.RUNTIME_TYPE_SECURITY_PREFIX = RUNTIME_TYPE_SECURITY_PREFIX;

    const RUNTIME_TYPE = {
        CONNECTION: RUNTIME_TYPE_PREFIX + 'connection',
        CONNECTOR: RUNTIME_TYPE_PREFIX + 'connector',
        ROUTE_CONTAINER: RUNTIME_TYPE_PREFIX + 'route-container',
        DEFAULT_ROUTE: RUNTIME_TYPE_PREFIX + 'default-route',
        ROUTE: RUNTIME_TYPE_PREFIX + 'route',
        PROFILE: RUNTIME_TYPE_PREFIX + 'profile',
        SERVICE: RUNTIME_TYPE_PREFIX + 'service',
        REPOSITORY: RUNTIME_TYPE_PREFIX + 'repository',
        CONFIG: RUNTIME_TYPE_PREFIX + 'config',
        ROUTE_LIBRARY: RUNTIME_TYPE_PREFIX + 'route-library',
    }
    Entaxy.RUNTIME_TYPE = RUNTIME_TYPE;

    const RUNTIME_TYPE_SECURITY = {
        JAAS_REALM: RUNTIME_TYPE_SECURITY_PREFIX + 'jaas.realm',
        JAAS_MODULE: RUNTIME_TYPE_SECURITY_PREFIX + 'jaas.loginmodule',
        KEY_STORE: RUNTIME_TYPE_SECURITY_PREFIX + 'keystore',
        VAULT: RUNTIME_TYPE_SECURITY_PREFIX + 'vault'
    }
    Entaxy.RUNTIME_TYPE_SECURITY = RUNTIME_TYPE_SECURITY;

    const SCOPE = {
        PRIVATE: 'private',
        PUBLIC: 'public'
    }
    Entaxy.SCOPE = SCOPE;

    const OBJECT_CLUSTER_STATE = {
        LOCAL: 'local',
        CLUSTERED: 'clustered',
        NON_CLUSTERED: 'non-clustered'
    }
    Entaxy.OBJECT_CLUSTER_STATE = OBJECT_CLUSTER_STATE;

    const NON_CLUSTERED_MESSAGE = {
        OPERATIONS: 'Cannot process operations on the object in the non-clustered state',
        EDITING: 'Non-clustered object cannot be edited'
    }
    Entaxy.NON_CLUSTERED_MESSAGE = NON_CLUSTERED_MESSAGE;

    const ERROR_MESSAGE = {
        INVALID: 'Invalid value',
        UNIQUE: 'Value must be unique',
        EMPTY: 'Please fill out this field',
        PASSWORD_CONFIRMATION: 'Password and confirmation password do not match'
    }
    Entaxy.ERROR_MESSAGE = ERROR_MESSAGE;

    const MODAL_CANCEL_REASON = {
        ESCAPE_KEY_PRESS: 'escape key press'
    }
    Entaxy.MODAL_CANCEL_REASON = MODAL_CANCEL_REASON;

    const CONFIRMATION = {
        UNSAVED_CHANGES: 'You have unsaved changes. Do you want to proceed anyway?'
    }
    Entaxy.CONFIRMATION = CONFIRMATION;

    const OPERATION_TYPE = {
        START: 'start',
        STOP: 'stop',
        UNINSTALL: 'uninstall'
    }
    Entaxy.OPERATION_TYPE = OPERATION_TYPE;

    function getButtonTitleByMode(mode) {
        switch (mode) {
            case MODAL_MODES.ADD:
                return 'Add';
            case MODAL_MODES.EDIT:
                return 'Save';
            case MODAL_MODES.VIEW:
                return 'Ok';
        }
    }
    Entaxy.getButtonTitleByMode = getButtonTitleByMode;

    function getItemTypeFromRuntimeType(runtimeType) {
        let runtimeTypeWithoutPrefix = runtimeType.startsWith(RUNTIME_TYPE_PREFIX) ?
            runtimeType.replace(RUNTIME_TYPE_PREFIX, '') :
            runtimeType.replace(RUNTIME_TYPE_SECURITY_PREFIX, '');
        let splitRuntimeTypeWithoutPrefix = runtimeTypeWithoutPrefix.split(/[.-]+/);
        return splitRuntimeTypeWithoutPrefix.map(item => capitalize(item)).join(' ');
    }
    Entaxy.getItemTypeFromRuntimeType = getItemTypeFromRuntimeType;

    let resourceCopyConfigs = {};
    Entaxy.resourceCopyConfigs = resourceCopyConfigs;

    function deepCopy(object) {
        return JSON.parse(JSON.stringify(object));
    }
    Entaxy.deepCopy = deepCopy;

    function capitalize(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    Entaxy.capitalize = capitalize;

    function uncapitalize(string) {
        return string.charAt(0).toLowerCase() + string.slice(1);
    }
    Entaxy.uncapitalize = uncapitalize;

    function stringToBase64(stringOrigin) {
        return bytesToBase64(new TextEncoder().encode(stringOrigin));
    }
    Entaxy.stringToBase64 = stringToBase64;

    function base64ToString(base64) {
        return (new TextDecoder().decode(base64ToBytes(base64)));
    }
    Entaxy.base64ToString = base64ToString;

    function bytesToBase64(bytes) {
        const binString = Array.from(bytes, (x) => String.fromCodePoint(x)).join("");
        return btoa(binString);
    }

    function base64ToBytes(base64) {
        const binString = atob(base64);
        return Uint8Array.from(binString, (m) => m.codePointAt(0));
    }

    function getChildrenRecursive(folder) {
        let children = folder.children;
        if (children) {
            folder.children.forEach(child => {
                if (child.children) {
                    children = children.concat(getChildrenRecursive(child));
                }
            });
        }
        return children;
    }
    Entaxy.getChildrenRecursive = getChildrenRecursive;

    function compare() {
        return function(a, b) {
            let valueA = a.toLowerCase();
            let valueB = b.toLowerCase();
            if (valueA < valueB) {
                return -1;
            }
            if (valueA > valueB) {
                return 1;
            }
            return 0;
        }
    }
    Entaxy.compare = compare;

    function compareBy(fieldName) {
        return function(a, b) {
            let valueA = a[fieldName].toLowerCase();
            let valueB = b[fieldName].toLowerCase();
            if (valueA < valueB) {
                return -1;
            }
            if (valueA > valueB) {
                return 1;
            }
            return 0;
        }
    }
    Entaxy.compareBy = compareBy;

    function getStandardPageConfig() {
        return {
            pageNumber: 1,
            pageSize: Entaxy.configuration[CONFIGURATION_KEYS.PAGE_SIZE],
            pageSizeIncrements: Entaxy.configuration[CONFIGURATION_KEYS.PAGE_SIZE_INCREMENTS]
        };
    }
    Entaxy.getStandardPageConfig = getStandardPageConfig;

    function applyFilters(items, filters, matchesFilterFn, extraClearFilterFn) {
        let viewedItems = [];
        if (filters && filters.length > 0) {
            items.forEach(function (item) {
                if (matchesFilters(item, filters, matchesFilterFn)) {
                    viewedItems.push(item);
                }
            });
        } else {
            viewedItems = items;

            if (extraClearFilterFn) {
                extraClearFilterFn(items);
            }
        }
        return viewedItems;
    };
    Entaxy.applyFilters = applyFilters;

    function matchesFilters(item, filters, matchesFilterFn) {
        let matches = true;
        filters.forEach(function(filter) {
            if (!matchesFilterFn(item, filter)) {
                matches = false;
                return false;
            }
        });
        return matches;
    };

    function convertToHtmlInputType(javaType) {
        if (!javaType || javaType.startsWith(RUNTIME_TYPE_PREFIX) || javaType.startsWith(RUNTIME_TYPE_SECURITY_PREFIX)) {
            return javaType;
        }
        switch (javaType) {
            case 'password':
            case 'xml:route':
            case 'list':
            case 'resource':
                return javaType;
            case 'Url':
                return 'url';
            case 'boolean':
            case 'Boolean':
            case 'java.lang.Boolean':
                return 'checkbox';
            case 'number':
            case 'int':
            case 'long':
            case 'java.lang.Integer':
            case 'java.lang.Long':
                return 'number';
            case 'map':
            case 'Map':
                return 'map';
            default:
                return 'text';
        }
    }
    Entaxy.convertToHtmlInputType = convertToHtmlInputType;

    const NOTIFICATION_TYPE = {
        SUCCESS: 'success',
        DANGER: 'danger',
        INFO: 'info',
        WARNING: 'warning'
    }
    Entaxy.NOTIFICATION_TYPE = NOTIFICATION_TYPE;

    function createTableFromResponse(response) {
        let tableHtml = `<table class="entaxy-result-table">`;
        tableHtml +=
        `
            <tr>
                <th>Step</th>
                <th>Step name</th>
                <th>Step result</th>
            </tr>
        `;
        _.forEach(response, (step) => {
            let iconName = step['Step result'] === 'OK' ? 'ok' : 'error-circle-o';
            tableHtml += `<tr><td>` + step['Step'] + `</td><td>` + step['Step name'] + `</td>`;
            tableHtml += `<td><span class="pficon pficon-${iconName}"></span></td></tr>`;
        });
        tableHtml += `</table>`;
        return tableHtml;
    }
    Entaxy.createTableFromResponse = createTableFromResponse;

    function getNotificationTypeFromResponse(response) {
        for (let i = 0; i < Object.keys(response).length; i++) {
            if (response[i.toString()]['Step result'] === 'Failed') {
                return NOTIFICATION_TYPE.DANGER;
            }
        }
        return NOTIFICATION_TYPE.SUCCESS;
    }
    Entaxy.getNotificationTypeFromResponse = getNotificationTypeFromResponse;

    function createTableFromOperationAffectedObjects(affectedObjects) {
        let tableHtml = `<table class="entaxy-result-table">`;
        tableHtml +=
        `
            <tr>
                <th>Object</th>
                <th>Operation</th>
            </tr>
        `;
        affectedObjects.forEach(object => {
            tableHtml += `<tr><td>` + object.objectId + `</td><td>` + object.action + `</td></tr>`;
        });
        tableHtml += `</table>`;
        return tableHtml;
    }
    Entaxy.createTableFromOperationAffectedObjects = createTableFromOperationAffectedObjects;

    function createStatusResultTable(result, header) {
        let tableHtml = `<table class="entaxy-result-table">`;
        tableHtml += `
            <tr>
                <th>` + header + `</th>
                <th>Status</th>
            </tr>
        `;
        result.forEach(res => {
            let iconName = res.failed ? 'error-circle-o' : 'ok';
            tableHtml += `<tr><td style="padding-right: 5px;">` + res.id +
                `</td><td><span class="pficon pficon-${iconName}"></span></td></tr>`;
        });
        tableHtml += `</table>`;
        return tableHtml;
    }
    Entaxy.createStatusResultTable = createStatusResultTable;

    function notificationWithDetails(type, mainMessage, message, duration) {
        let toastHtml = `
            <div class="toast-pf alert alert-${type} alert-dismissable">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">
                    <span class="pficon pficon-close"></span>
                </button>
                <span class="pficon pficon-${resolveToastIcon(type)}"></span>
                <div class="toast-pf-content">
                    <div class="entaxy-notification-main-message">
                        ${mainMessage}
                        <div class="pull-right toast-pf-action">
                            <a id="show-notification-details" onclick="showNotificationDetails()">
                                Show details...
                            </a>
                            <a id="hide-notification-details" onclick="hideNotificationDetails()" hidden>
                                Hide details...
                            </a>
                        </div>
                    </div>
                    <div id="notification-message-details" hidden>
                        ${message}
                    </div>
                </div>
                <script>
                    function showNotificationDetails () {
                        document.getElementById('notification-message-details').hidden = false;
                        document.getElementById('hide-notification-details').hidden = false;
                        document.getElementById('show-notification-details').hidden = true;
                    }
                    function hideNotificationDetails() {
                        document.getElementById('notification-message-details').hidden = true;
                        document.getElementById('hide-notification-details').hidden = true;
                        document.getElementById('show-notification-details').hidden = false; 
                    }
                </script>
            </div>
        `;
        createNotification(type, toastHtml, duration);
    }
    Entaxy.notificationWithDetails = notificationWithDetails;

    function notification(type, message, duration) {
        let toastHtml = `
          <div class="toast-pf alert alert-${type} alert-dismissable">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">
              <span class="pficon pficon-close"></span>
            </button>
            <span class="pficon pficon-${resolveToastIcon(type)}"></span>
            ${message}
          </div>
        `;
        createNotification(type, toastHtml, duration);
    }
    Entaxy.notification = notification;

    function createNotification(type, toastHtml, duration) {
        let visibleToastElem = null;
        let timeoutId;

        let toastFrag = document.createRange().createContextualFragment(toastHtml);
        let toastElem = toastFrag.querySelector('div');

        let bodyElem = document.querySelector('body');

        // if toast element is in the DOM
        if (visibleToastElem && visibleToastElem.parentNode) {
            clearTimeout(timeoutId);
            bodyElem.removeChild(visibleToastElem);
        }
        visibleToastElem = bodyElem.appendChild(toastElem);

        if (duration || (type === NOTIFICATION_TYPE.SUCCESS || type === NOTIFICATION_TYPE.INFO)) {
            timeoutId = window.setTimeout(() => {
                let notificationDetails = toastElem.querySelector('#notification-message-details');
                if ((!notificationDetails || notificationDetails.hidden) && toastElem.parentNode) {
                    bodyElem.removeChild(toastElem);
                }
            }, duration || Entaxy.configuration[CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_INFO]);
        }
    }

    function resolveToastIcon(type) {
        switch (type) {
            case NOTIFICATION_TYPE.SUCCESS:
                return 'ok';
            case NOTIFICATION_TYPE.WARNING:
                return 'warning-triangle-o';
            case NOTIFICATION_TYPE.DANGER:
                return 'error-circle-o';
            default:
                return 'info';
        }
    }

    function notificationInfo(message) {
        Core.notification(NOTIFICATION_TYPE.INFO, message,
            Entaxy.configuration[CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_INFO]);
    }
    Entaxy.notificationInfo = notificationInfo;

    function notificationSuccess(message) {
        Core.notification(NOTIFICATION_TYPE.SUCCESS, message,
            Entaxy.configuration[CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_SUCCESS]);
    }
    Entaxy.notificationSuccess = notificationSuccess;

    function notificationError(message) {
        Core.notification(NOTIFICATION_TYPE.DANGER, message,
            Entaxy.configuration[CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_ERROR]);
    }
    Entaxy.notificationError = notificationError;

    function changingFieldValueNotification(fieldDescriptor) {
        Core.notification(Entaxy.NOTIFICATION_TYPE.WARNING,
            'Changing ' + fieldDescriptor +
            ' field value may lead to changes in other fields of the current object. ' +
            'Please, make sure to revise all fields before accepting.',
            Entaxy.configuration[Entaxy.CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_INFO]);
    }
    Entaxy.changingFieldValueNotification = changingFieldValueNotification;

    function setDefaultConfiguration() {
        Entaxy.configuration = getDefaultConfiguration();
    }
    Entaxy.setDefaultConfiguration = setDefaultConfiguration;

    function setConfiguration(configuration) {
        let defaultConfiguration = getDefaultConfiguration();
        Object.keys(defaultConfiguration).forEach(key => {
            if (configuration[key] === undefined) {
                Entaxy.log.error('Configuration file ru.entaxy.esb.ui.hawtio does not have property ' + key +
                    ', property value is set to default');
                configuration[key] = defaultConfiguration[key];
            }
        });
        Entaxy.configuration = configuration;
    }
    Entaxy.setConfiguration = setConfiguration;

    const CONFIGURATION_KEYS = {
        NOTIFICATION_TIMEOUT_SUCCESS: 'notification.timeout.success',
        NOTIFICATION_TIMEOUT_ERROR: 'notification.timeout.error',
        NOTIFICATION_TIMEOUT_INFO: 'notification.timeout.info',
        NOTIFICATION_TIMEOUT_TABLE: 'notification.timeout.table',
        PAGE_SIZE: 'page.size',
        PAGE_SIZE_INCREMENTS: 'page.size.increments',
        HEALTHCHECK_INTERVAL: 'healthcheck.interval'
    }
    Entaxy.CONFIGURATION_KEYS = CONFIGURATION_KEYS;

    function getDefaultConfiguration() {
        return {
            [CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_SUCCESS]: 5000,
            [CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_ERROR]: 5000,
            [CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_INFO]: 8000,
            [CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_TABLE]: 10000,
            [CONFIGURATION_KEYS.PAGE_SIZE]: 10,
            [CONFIGURATION_KEYS.PAGE_SIZE_INCREMENTS]: [5, 10, 20, 50, 100],
            [CONFIGURATION_KEYS.HEALTHCHECK_INTERVAL]: 15000
        }
    }

})(Entaxy || (Entaxy = {}));
