/*-
 * ~~~~~~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('entaxyCiCdProjectVersions', {
        template:
        `
          <div class="entaxy-cicd-content-with-title-container">
            <h2>{{$ctrl.title}}</h2>

            <pf-toolbar class="entaxy-toolbar" config="$ctrl.toolbarConfig">
              <actions>
                <span class="dropdown primary-action" uib-dropdown>
                  <button class="dropdown-toggle" uib-dropdown-toggle type="button">
                    Add Version
                    <span class="caret"></span>
                  </button>
                  <ul class="dropdown-menu">
                    <li role="menuitem" ng-click="$ctrl.addVersionFromScratch()">
                      <a class="secondary-action">Add Version From Scratch</a>
                    </li>
                    <li role="menuitem" ng-click="$ctrl.addVersionFromExistent()">
                      <a class="secondary-action">Add Version From Existent</a>
                    </li>
                  </ul>
                </span>
              </actions>
            </pf-toolbar>
            <pf-table-view class="entaxy-cicd-table"
                          config="$ctrl.tableConfig"
                          columns="$ctrl.tableColumns"
                          action-buttons="$ctrl.tableActionButtons"
                          page-config="$ctrl.pageConfig"
                          items="$ctrl.viewedItems">
            </pf-table-view>  
          </div>
        `,
        controller: entaxyCICDProjectVersionsController
    })
        .name;

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

        let ctrl = this;

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

        ctrl.toolbarConfig = {
            filterConfig: {
                fields: [
                    {
                        id: 'name',
                        title: 'Name',
                        placeholder: 'Filter by Name...',
                        filterType: 'text'
                    },
                    {
                        id: 'isBuilt',
                        title: 'Build Available',
                        placeholder: 'Filter by Built Availability...',
                        filterType: 'select',
                        filterValues: ['yes', 'no']
                    }
                ],
                appliedFilters: [],
                onFilterChange: filterChange
            },
            actionsConfig: {
                actionsInclude: true
            },
            isTableView: true
        };

        ctrl.tableColumns = [
            {
                header: 'Name',
                itemField: 'name',
                htmlTemplate: 'project/version/name.html',
                colActionFn: (name) => ctrl.changeLocation(name)
            },
            { header: 'Build Available', itemField: 'isBuilt',
                templateFn: (value) => EntaxyCICD.getStatusTemplate(value) }
        ];

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

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

        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 === 'isBuilt') {
                match = filter.value === 'yes' ? item.isBuilt === true : item.isBuilt === false;
            }
            return match;
        };

        ctrl.$onInit = function() {

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

            ctrl.title = 'Versions';

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

            populateTable();
        }

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

        function populateTable() {
            let selectedProject = workspace.selection;
            if (selectedProject.children && selectedProject.children.length > 0) {
                let versions = [];
                selectedProject.children.forEach(version => {
                    versions.push({
                        name: version.title,
                        isBuilt: version.children && version.children.length === 1 ? true : false
                    });
                });

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

        function getFormFields() {
            return [
                {
                    label: 'Created Version',
                    name: 'createdVersion',
                    type: 'text',
                    required: true,
                    validation: {
                        checkUniqueness: true,
                        values: ctrl.items.map(version => version.name),
                        content: {
                            regex: '^([1-9][0-9]*|0)\\.([1-9][0-9]*|0)\\.([1-9][0-9]*|0)$',
                            errorMessage: 'Value must match the pattern: X.X.X, where X represents a number'
                        }
                    },
                    setFocused: true
                }
            ];
        }

        ctrl.addVersionFromScratch = function () {
            openCreateVersionModal(getFormFields());
        }

        ctrl.addVersionFromExistent = function () {
            let formFields = getFormFields();
            formFields.push({
                label: 'Prototype Version',
                name: 'prototypeVersion',
                enum: true,
                required: true,
                values: ctrl.items.map(version => version.name)
            });
            openCreateVersionModal(formFields);
        }

        function openCreateVersionModal(formFields) {
            $uibModal.open({
                component: 'entaxyCiCdSimpleFieldsModal',
                resolve: {
                    modalTitle: () => 'Create Version',
                    formFields: () => formFields
                },
                backdrop: 'static'
            }).result.then((args) => {
                createVersion(...args);
            }, reason => {
                if (reason && reason !== Entaxy.MODAL_CANCEL_REASON.ESCAPE_KEY_PRESS) {
                    Entaxy.notificationError(reason);
                }
            });
        }

        function createVersion(createdVersion, prototypeVersion) {
            entaxyCICDService.executeOperation('createVersion',
                [ctrl.storage, ctrl.project, createdVersion, prototypeVersion])
            .then(result => {
                Entaxy.notificationSuccess(result);
                entaxyCICDService.treeUpdated();
            }).catch(error => {
                Entaxy.notificationError(error);
                EntaxyCICD.log.error(error);
            });
        }

        function removeVersion(action, item) {
            let properties = [ctrl.storage, ctrl.project, item.name];
            entaxyCICDService.removeItemWithConfirmation(EntaxyCICD.ITEM_TYPE.VERSION, item.name, properties);
        }
    }
    entaxyCICDProjectVersionsController.$inject = ['$scope', 'workspace', 'entaxyCICDService', '$uibModal',
        '$templateCache', '$location'];

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