/*-
 * ~~~~~~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('entaxyCiCdVersionsRevisionsInfo', {
        template:
        `
          <div class="entaxy-cicd-content-with-title-container">
            <h2>Versions & Revisions</h2>
          
            <pf-toolbar class="entaxy-toolbar" config="$ctrl.toolbarConfig"></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>
          </div>
        `,
        controller: EntaxyCICDVersionsRevisionsInfoController
    })
    .name;

    function EntaxyCICDVersionsRevisionsInfoController(workspace, entaxyCICDService, $q, $templateCache, $location) {
        'ngInject';

        let ctrl = this;

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

        ctrl.toolbarConfig = {
            filterConfig: {
                fields: [
                    {
                        id: 'version',
                        title: 'Version',
                        placeholder: 'Filter by Version...',
                        filterType: 'text'
                    },
                    {
                        id: 'installedRevision',
                        title: 'Installed Revision Presence',
                        placeholder: 'Filter by Installed Revision Presence...',
                        filterType: 'select',
                        filterValues: ['present', 'not present']
                    }
                ],
                inlineResults: true,
                appliedFilters: [],
                onFilterChange: filterChange
            },
            isTableView: true
        };

        ctrl.tableColumns = [
            {
                header: 'Version',
                itemField: 'version',
                htmlTemplate: 'application/version.html',
                colActionFn: (version) => ctrl.changeLocation(version)
            },
            { header: 'Last Revision', itemField: 'lastRevision' },
            { header: 'Installed Revision', itemField: 'installedRevision' }
        ];

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

        ctrl.changeLocation = function (version) {
            let nid = $location.search().nid;
            $location.search('nid', nid + '-' + version);
        }

        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 === 'version') {
                match = item.version.match(filter.value) !== null;
            } else if (filter.id === 'installedRevision') {
                match = filter.value === 'present' ? item.installedRevision !== '-' : item.installedRevision === '-';
            }
            return match;
        };

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

        ctrl.$onInit = function() {

            ctrl.storage = EntaxyCICD.getStorage(workspace.selection);

            ctrl.tableActionButtons = [
                { name: 'Remove Version', title: 'Remove Version', actionFn: removeVersion }
            ];

            populateTable();
        }

        function populateTable() {

            const applicationFolder = workspace.selection;

            let items = [];
            let promises = [];
            if (applicationFolder.children && applicationFolder.children.length > 0) {
                applicationFolder.children.forEach(versionFolder => {
                    promises.push(
                        entaxyCICDService.executeOperation('readApplicationVersionLastAndInstalledRevision',
                            [ctrl.storage, applicationFolder.title, versionFolder.title])
                        .then(result => {
                            let revisionsInfo = JSON.parse(result);
                            items.push({
                                version: versionFolder.title,
                                lastRevision: revisionsInfo.lastRevision,
                                installedRevision: revisionsInfo.installedRevision
                            });
                        })
                    );
                });
            }
            $q.all(promises).then(() => {
                ctrl.items = items;
                filterChange(ctrl.toolbarConfig.filterConfig.appliedFilters);
            });
        }

        function removeVersion(action, item) {
            let application = workspace.selection.title;

            if (ctrl.items.length > 1) {
                let properties = [ctrl.storage, application, item.version];
                entaxyCICDService.removeItemWithConfirmation(EntaxyCICD.ITEM_TYPE.VERSION, item.version, properties);
            } else {
                let properties = [ctrl.storage, application];
                let message = 'Removing the last version of the application will lead to removing the application. ' +
                    'Do you want to proceed?';
                entaxyCICDService.removeItemWithConfirmation(EntaxyCICD.ITEM_TYPE.APPLICATION, null, properties,
                    false, message);
            }

        }
    }
    EntaxyCICDVersionsRevisionsInfoController.$inject = ['workspace', 'entaxyCICDService', '$q', '$templateCache',
        '$location'];

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