/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2023 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;

    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) {
        return runtimeType.replace('entaxy.runtime.', '');
    }
    Entaxy.getItemTypeFromRuntimeType = getItemTypeFromRuntimeType;

    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 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 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: 10,
            pageSizeIncrements: [5, 10, 20, 50, 100]
        };
    }
    Entaxy.getStandardPageConfig = getStandardPageConfig;

    function applyFilters(items, filters, matchesFilterFn) {
        let viewedItems = [];
        if (filters && filters.length > 0) {
            items.forEach(function (item) {
                if (matchesFilters(item, filters, matchesFilterFn)) {
                    viewedItems.push(item);
                }
            });
        } else {
            viewedItems = 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('entaxy.runtime')) {
            return javaType;
        }
        switch (javaType) {
            case 'password':
            case 'xml:route':
                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';
            default:
                return 'text';
        }
    }
    Entaxy.convertToHtmlInputType = convertToHtmlInputType;

    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(JSON.parse(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 notification(type, message, duration) {

        let visibleToastElem = null;
        let timeoutId;

        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">
                    ${message}
                </div>
            </div>
        `;

        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 === 'success' || type === 'info')) {
            timeoutId = window.setTimeout(() => {
                if (toastElem.parentNode) {
                    bodyElem.removeChild(toastElem);
                }
            }, duration || 8000);
        }
    }
    Entaxy.notification = notification;

    function resolveToastIcon(type) {
        switch (type) {
            case 'success':
                return 'ok';
            case 'warning':
                return 'warning-triangle-o';
            case 'danger':
                return 'error-circle-o';
            default:
                return 'info';
        }
    }

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