/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-cicd-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 EntaxyCICD;
(function (EntaxyCICD) {
    EntaxyCICD._module.component('entaxyCiCdApplicationsTable', {
        bindings: {
            type: '@',
            importFromFile: '<',
            importFromRepository: '<',
            createProject: '<'
        },
        template:
        `
          <pf-toolbar class="entaxy-toolbar" config="$ctrl.toolbarConfig">
            <actions>
              <span class="dropdown primary-action" uib-dropdown>
                <button class="btn btn-default dropdown-toggle" uib-dropdown-toggle type="button">
                  Import
                  <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                  <li role="menuitem" ng-click="$ctrl.importFromFile()">
                    <a class="secondary-action">Import From File</a>
                  </li>
                  <li role="menuitem" ng-click="$ctrl.importFromRepository()">
                    <a class="secondary-action">Import From Repository</a>
                  </li>
                </ul>
              </span>
            </actions>
          </pf-toolbar>
          <pf-table-view config="$ctrl.tableConfig"
                        columns="$ctrl.tableColumns"
                        action-buttons="$ctrl.tableActionButtons"
                        page-config="$ctrl.pageConfig"
                        items="$ctrl.viewedItems">
          </pf-table-view>
        `,
        controller: EntaxyCICDApplicationsTableController
    })
        .name;

    function EntaxyCICDApplicationsTableController(workspace, $uibModal, entaxyCICDService, $templateCache, $location) {
        'ngInject';

        let ctrl = this;

        const isStorageSelected = EntaxyCICD.isStorage(workspace.selection);

        ctrl.tableConfig = {
            selectionMatchProp: 'name',
            showCheckboxes: false
        };

        ctrl.toolbarConfig = {
            filterConfig: {
                fields: [
                    {
                        id: 'name',
                        title: 'Name',
                        placeholder: 'Filter by Name...',
                        filterType: 'text'
                    }
                ],
                appliedFilters: [],
                onFilterChange: filterChange
            },
            isTableView: true
        };

        ctrl.tableColumns = [
            {
                header: 'Name',
                itemField: 'name',
                htmlTemplate: 'applications/table/name.html',
                colActionFn: (name) => ctrl.changeLocation(name)
            }
        ];

        $templateCache.put(
            'applications/table/name.html',
            '<a href="" ng-click="$ctrl.handleColAction(key, value)">{{value}}</a>'
        );

        ctrl.changeLocation = function (name) {
            let nid = $location.search().nid;
            if (isStorageSelected) {
                $location.search('nid', nid + '-' + name);
            } else {
                let item = ctrl.viewedItems.find(viewedItem => viewedItem.name === name);
                $location.search('nid', [nid, item.storage, name].join('-'));
            }
        }

        if (!isStorageSelected) {
            ctrl.tableColumns.push({ header: 'Storage', itemField: 'storage' });

            ctrl.toolbarConfig.filterConfig.fields.push({
                id: 'storage',
                title: 'Storage',
                placeholder: 'Filter by Storage...',
                filterType: 'select',
                filterValues: EntaxyCICD.getStorages(workspace.selection)
            });
        }

        ctrl.pageConfig = Entaxy.getStandardPageConfig();

        function filterChange(filters) {
            ctrl.viewedItems = Entaxy.applyFilters(ctrl.items, filters, matchesFilter);
            ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedItems.length;
        };

        function matchesFilter(item, filter) {
            let match = true;
            if (filter.id === 'name') {
                match = item.name.toLowerCase().match(filter.value.toLowerCase()) !== null;
            } else if (filter.id === 'storage') {
                match = item.storage === filter.value;
            }
            return match;
        };

        ctrl.items = [];
        ctrl.viewedItems = [];

        ctrl.$onInit = function() {

            populateTable();

            if (ctrl.type === EntaxyCICD.ITEM_TYPE.APPLICATION) {
                ctrl.toolbarConfig.actionsConfig = {
                    actionsInclude: true
                };

                ctrl.tableColumns.push({
                    header: 'Versions & Revisions',
                    itemField: 'versionsRevisionsInfo',
                    templateFn: (value) => getVersionsRevisionsColumnTemplate(value)
                });

            } else if (ctrl.type === EntaxyCICD.ITEM_TYPE.PROJECT) {
                let primaryActions = [{name: 'Create ' + ctrl.type, actionFn: () => ctrl.createProject(ctrl.items)}];

                ctrl.toolbarConfig.actionsConfig = {
                    primaryActions: primaryActions
                };
            }

            ctrl.tableActionButtons = [
                { name: 'Remove', title: 'Remove ' + ctrl.type, actionFn: removeItem }
            ];
        }

        function getVersionsRevisionsColumnTemplate(value) {
            const DIV = {
                OPEN: '<div>',
                CLOSE: '</div>'
            };
            const CLASS_INSTALLED = 'class="entaxy-cicd-installed"';
            function insert(string, index, substring) {
                return string.slice(0, index) + substring + string.slice(index);
            }
            const spanOpen = '<span data-toggle="tooltip" title="">';
            const SPAN = {
                OPEN: {
                    VERSION: insert(spanOpen, -2, 'Version'),
                    LAST_REVISION: insert(spanOpen, -2, 'Last Revision'),
                    INSTALLED_REVISION: insert(spanOpen, -2, 'Installed Revision')
                },
                CLOSE: '</span>'
            };
            let result = DIV.OPEN;
            value = value.sort(Entaxy.compareBy('version'));
            value.forEach(item => {
                const versionOpeningSpan = item.installedRevision !== '-' ?
                    insert(SPAN.OPEN.VERSION, 5, ' ' + CLASS_INSTALLED) :
                    SPAN.OPEN.VERSION;
                const revisionOpeningSpan = item.installedRevision !== '-' ?
                    insert(SPAN.OPEN.INSTALLED_REVISION, 5, ' ' + CLASS_INSTALLED) :
                    SPAN.OPEN.INSTALLED_REVISION;

                result = result +
                    DIV.OPEN +
                    versionOpeningSpan + item.version + SPAN.CLOSE +
                    SPAN.OPEN.LAST_REVISION + item.lastRevision + SPAN.CLOSE +
                    revisionOpeningSpan + item.installedRevision + SPAN.CLOSE +
                    DIV.CLOSE;
            });
            return result + DIV.CLOSE;
        }

        function populateTable() {

            let items = [];

            if (isStorageSelected) {
                items = getItemsFromChildren(workspace.selection);
            } else {
                let storages = workspace.selection.children;
                if (storages && storages.length > 0) {
                    storages.forEach(storage => {
                        items = getItemsFromChildren(storage);
                    });
                }
            }

            if (ctrl.type === EntaxyCICD.ITEM_TYPE.APPLICATION) {
                items.forEach(item => {
                    if (item.versions) {
                        item.versionsRevisionsInfo = [];
                        item.versions.forEach(version => {
                            entaxyCICDService.executeOperation('readApplicationVersionLastAndInstalledRevision',
                                [item.storage, item.name, version])
                            .then(result => {
                                let revisionsInfo = JSON.parse(result);
                                item.versionsRevisionsInfo.push({
                                    version: version,
                                    lastRevision: revisionsInfo.lastRevision,
                                    installedRevision: revisionsInfo.installedRevision
                                });
                            });
                        });
                    }
                });
            }

            ctrl.items = items;
            filterChange(ctrl.toolbarConfig.filterConfig.appliedFilters);
        }

        function getItemsFromChildren(selection) {
            let items = [];
            if (selection.children && selection.children.length > 0) {
                selection.children.forEach(item => {
                    items.push({
                        name: item.title,
                        storage: selection.title,
                        versions: ctrl.type === EntaxyCICD.ITEM_TYPE.APPLICATION
                                    && item.children && item.children.length > 0 ?
                            item.children.map(child => child.title) : undefined
                    });
                });
            }
            return items;
        }

        function removeItem(action, item) {
            let properties = [item.storage, item.name];
            entaxyCICDService.removeItemWithConfirmation(ctrl.type, item.name, properties, true);
        }
    }
    EntaxyCICDApplicationsTableController.$inject = ['workspace', '$uibModal', 'entaxyCICDService',
        '$templateCache', '$location'];

})(EntaxyCICD || (EntaxyCICD = {}));
