/*-
 * ~~~~~~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('entaxyCiCdConfigurations', {
        bindings: {
            changeSelection: '<',
            configured: '<'
        },
        template:
        `
          <pf-toolbar class="entaxy-toolbar" config="$ctrl.toolbarConfig"></pf-toolbar>
          <div class="entaxy-cicd-objects-table-container">
            <pf-table-view config="$ctrl.tableConfig"
                          columns="$ctrl.tableColumns"
                          items="$ctrl.viewedItems">
            </pf-table-view>
          </div>
        `,
        controller: EntaxyCICDConfigurationsController
    })
    .name;

    function EntaxyCICDConfigurationsController(workspace, $q, entaxyCICDService, $templateCache, $route) {
        'ngInject';

        let ctrl = this;

        ctrl.tableConfig = {
            selectionMatchProp: 'id'
        };

        function changeSelected(item) {
            if (ctrl.selected[item.id]) {
                delete ctrl.selected[item.id];
            } else {
                ctrl.selected[item.id] = item;
            }
        }

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

        ctrl.tableColumns = [
            {
                header: 'Id',
                itemField: 'id',
                htmlTemplate: 'configurations/id.html',
                colActionFn: (configurationId) => ctrl.changeSelection(configurationId)
            },
            { header: 'Location', itemField: 'location' }
        ];

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

        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 === 'id') {
                match = item.id.toLowerCase().match(filter.value.toLowerCase()) !== null;
            }
            return match;
        };

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

        ctrl.$onInit = function() {
            ctrl.tableConfig.showCheckboxes = ctrl.configured;

            if (ctrl.configured) {
                ctrl.selected = {};
                ctrl.tableConfig.onCheckBoxChange = (item) => changeSelected(item);

                let primaryActions = [
                    {name: 'Set Local Values', actionFn: useLocalValues}
                ];

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

            ctrl.storage = EntaxyCICD.getStorage(workspace.selection);
            ctrl.application = EntaxyCICD.getProjectOrApplication(workspace.selection);
            ctrl.version = EntaxyCICD.getVersion(workspace.selection);
            ctrl.revision = workspace.selection.title.split(' ')[0];

            populateTable();
        }

        function populateTable() {
            entaxyCICDService.executeOperation('listRevisionConfigurations',
                [ctrl.storage, ctrl.application, ctrl.version, ctrl.revision])
            .then(result => {
                let items = JSON.parse(result);
                ctrl.items = items;
                filterChange(ctrl.toolbarConfig.filterConfig.appliedFilters);
            });
        }

        function useLocalValues() {
            let selectedIds = Object.keys(ctrl.selected);
            if (selectedIds.length > 0) {
                let promises = [];
                let failedIds = [];
                selectedIds.forEach(id => {
                    promises.push(
                        entaxyCICDService.executeOperation('fillInRevisionConfigurationWithLocalValues',
                            [ctrl.storage, ctrl.application, ctrl.version, ctrl.revision, id])
                        .catch(error => {
                            failedIds.push(id);
                            EntaxyCICD.log.error(error);
                        })
                    );
                });
                $q.all(promises).then(result => {
                    if (failedIds.length > 0) {
                        let result = selectedIds.map(id => {
                            return {
                                id: id,
                                failed: failedIds.includes(id)
                            };
                        });
                        let tableHtml = Entaxy.createStatusResultTable(result, 'Configuration Id');
                        let mainMessage = 'Some configurations were skipped ' +
                            'while setting local values due to errors that have occurred';
                        Entaxy.notificationWithDetails(Entaxy.NOTIFICATION_TYPE.WARNING, mainMessage, tableHtml,
                            Entaxy.configuration[Entaxy.CONFIGURATION_KEYS.NOTIFICATION_TIMEOUT_TABLE]);
                    } else {
                        Entaxy.notificationSuccess('Values of selected configurations were successfully ' +
                            'set to values of local configurations');
                    }
                    $route.reload();
                }).catch(error => {
                    Entaxy.notificationError(error);
                    EntaxyCICD.log.error(error);
                });
            }
        }
    }
    EntaxyCICDConfigurationsController.$inject = ['workspace', '$q', 'entaxyCICDService', '$templateCache', '$route'];

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