/*-
 * ~~~~~~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('entaxyCiCdProject', {
        template:
        `
          <div ng-if="$ctrl.versions || $ctrl.isVersionSelected">
            <div class="entaxy-cicd-header-container">
              <div class="entaxy-cicd-title-with-info-container">
                <span class="first" ng-class="{'lead': !$ctrl.isVersionSelected}">Project: {{$ctrl.project}}</span>
                <span class="lead" ng-if="$ctrl.isVersionSelected">Version: {{$ctrl.version}}</span>
                <div ng-if="!$ctrl.isVersionSelected">
                  <span>Version:</span>
                  <entaxy-select-from-enum values="$ctrl.versions" model="$ctrl.version"
                            is-empty-included="false"></entaxy-select-from-enum>
                            
                  <div class="btn-group" uib-dropdown>
                    <button id="single-button" type="button" uib-dropdown-toggle ng-disabled="disabled">
                      Add Version
                      <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" uib-dropdown-menu role="menu" aria-labelledby="single-button">
                      <li role="menuitem"><a ng-click="$ctrl.addVersionFromScratch()">Add Version From Scratch</a></li>
                      <li role="menuitem"><a ng-click="$ctrl.addVersionFromExistent()">Add Version From Existent</a></li>
                    </ul>
                  </div>       
                </div>
              </div>
              <div class="entaxy-cicd-header-buttons-container">
                <button type="button" ng-click="$ctrl.commit()">Commit</button>
                <button type="button" ng-click="$ctrl.build()">Build</button>
              </div>
            </div>
            
            <div class="entaxy-cicd-content-container">
              <entaxy-ci-cd-objects storage="$ctrl.storage" project="$ctrl.project" version="$ctrl.version"
                        ng-if="$ctrl.version"></entaxy-ci-cd-objects>
            </div>
          </div>    
        `,
        controller: entaxyCICDProjectController
    })
    .name;

    function entaxyCICDProjectController(workspace, entaxyCICDService, $uibModal) {
        'ngInject';

        let ctrl = this;

        ctrl.$onInit = function() {

            ctrl.storage = EntaxyCICD.getStorage(workspace.selection);
            ctrl.project = EntaxyCICD.getProjectOrApplication(workspace.selection);
            ctrl.isVersionSelected = EntaxyCICD.isVersion(workspace.selection);

            if (ctrl.isVersionSelected) {
                ctrl.version = workspace.selection.title;
            } else {
                populateVersions();
            }
        }

        function populateVersions() {
            ctrl.versions = EntaxyCICD.getVersions(workspace.selection);
            if (ctrl.versions.length > 0) {
                ctrl.version = ctrl.versions[ctrl.versions.length - 1];
            }
        }

        function getFormFields() {
            return [
                {
                    label: 'Current Version',
                    name: 'currentVersion',
                    type: 'text',
                    value: ctrl.version,
                    readOnly: true
                },
                {
                    label: 'Created Version',
                    name: 'createdVersion',
                    type: 'text',
                    required: true,
                    validation: {
                        checkUniqueness: true,
                        values: ctrl.versions,
                        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.versions,
                value: ctrl.version
            });
            openCreateVersionModal(formFields);
        }

        function openCreateVersionModal(formFields) {
            $uibModal.open({
                component: 'entaxyCiCdSimpleFieldsModal',
                resolve: {
                    modalTitle: () => 'Create Version',
                    formFields: () => formFields
                },
                backdrop: 'static'
            }).result.then((args) => {
                args.shift();
                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);
            });
        }

        ctrl.commit = function () {
            processOperation('saveProjectVersion');
        }

        ctrl.build = function () {
            processOperation('buildProjectVersion');
        }

        function processOperation(operationName) {
            entaxyCICDService.executeOperation(operationName, [ctrl.storage, ctrl.project, ctrl.version])
            .then(result => {
                Entaxy.notificationSuccess(result);

                if (operationName === 'buildProjectVersion') {
                    workspace.jmxTreeUpdated();
                }
            }).catch(error => {
                Entaxy.notificationError(error);
                EntaxyCICD.log.error(error);
            });
        }
    }
    entaxyCICDProjectController.$inject = ['workspace', 'entaxyCICDService', '$uibModal'];

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