/*-
 * ~~~~~~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('entaxyCiCdApplication', {
        template:
        `
          <div class="entaxy-cicd-zero-revision-note" ng-if="$ctrl.isRevisionSelected && $ctrl.revision === '0'">
            <entaxy-form-field-extra-info type="'info'" message="$ctrl.zeroRevisionNote"></entaxy-form-field-extra-info>
          </div>
          <div ng-if="$ctrl.versions || $ctrl.isVersionSelected || $ctrl.isRevisionSelected"
                class="entaxy-cicd-header-container">
            <div class="entaxy-cicd-title-with-info-container">
              <span class="first" ng-class="{'lead': !$ctrl.isVersionSelected && !$ctrl.isRevisionSelected}">
                Application: {{$ctrl.application}}
              </span>
              <span ng-class="{'lead': $ctrl.isVersionSelected}" 
                    ng-if="$ctrl.isVersionSelected || $ctrl.isRevisionSelected">
                Version: {{$ctrl.version}}
              </span>
              <div ng-if="!$ctrl.isVersionSelected && !$ctrl.isRevisionSelected">
                <span>Version:</span>
                <entaxy-select-from-enum values="$ctrl.versions" model="$ctrl.version"
                          is-empty-included="false"></entaxy-select-from-enum>                        
              </div>
              <span ng-if="$ctrl.isVersionSelected">
                Last Revision: {{$ctrl.lastRevision}}
              </span>
              <span ng-if="$ctrl.isVersionSelected">
                Installed Revision: {{$ctrl.installedRevision}}
              </span>
              <span class="lead" ng-if="$ctrl.isRevisionSelected">
                Revision: {{$ctrl.revision}}
              </span>
              <span ng-if="$ctrl.isRevisionSelected">
                Revision Status: {{$ctrl.revisionStatus}}
              </span>
            </div>
            <div ng-if="$ctrl.isRevisionSelected" class="entaxy-cicd-header-buttons-container">
              <entaxy-ci-cd-application-management-buttons storage="$ctrl.storage" application="$ctrl.application"
                        version="$ctrl.version" revision="$ctrl.revision" revision-status="$ctrl.revisionStatus">
              </entaxy-ci-cd-application-management-buttons>
            </div>
            <div class="dropdown primary-action entaxy-cicd-header-buttons-container"
                    uib-dropdown ng-if="$ctrl.isVersionSelected">
              <button class="dropdown-toggle" uib-dropdown-toggle type="button">
                Add Revision
                <span class="caret"></span>
              </button>
              <ul class="dropdown-menu dropdown-menu-right">
                <li role="menuitem" ng-click="$ctrl.addRevision()">
                  <a class="secondary-action">Add Revision</a>
                </li>
                <li role="menuitem" ng-click="$ctrl.addRevisionFromExistent()">
                  <a class="secondary-action">Add Revision From Existent</a>
                </li>
              </ul>
            </div>
          </div>
          
          <div class="entaxy-cicd-content-container">
            <h2 class="first">
              Items
            </h2>
            
            <entaxy-ci-cd-application-items version="$ctrl.version"></entaxy-ci-cd-application-items>
              
            <h2>
              Requirements
            </h2>
              
            <entaxy-ci-cd-requirements version="$ctrl.version" type="Application"></entaxy-ci-cd-requirements>
          </div>
        `,
        controller: EntaxyCICDApplicationController
    })
        .name;

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

        let ctrl = this;
        ctrl.zeroRevisionNote = 'Revision 0 cannot be configured';

        ctrl.$onInit = function() {

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

            ctrl.isVersionSelected = EntaxyCICD.isVersion(workspace.selection);
            ctrl.isRevisionSelected = EntaxyCICD.isRevision(workspace.selection);

            if (ctrl.isVersionSelected || ctrl.isRevisionSelected) {
                ctrl.version = EntaxyCICD.getVersion(workspace.selection);

                if (ctrl.isRevisionSelected) {
                    let revisionInfo = EntaxyCICD.getRevisionInfo(workspace.selection);
                    ctrl.revision = revisionInfo.revision;
                    ctrl.revisionStatus = revisionInfo.revisionStatus;
                } else {
                    entaxyCICDService.executeOperation('readApplicationVersionLastAndInstalledRevision',
                        [ctrl.storage, ctrl.application, ctrl.version])
                    .then(result => {
                        let revisionsInfo = JSON.parse(result);
                        ctrl.lastRevision = revisionsInfo.lastRevision;
                        ctrl.installedRevision = revisionsInfo.installedRevision;
                    });
                }
            } else {
                populateVersions();
            }
        }

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

        ctrl.addRevision = function () {
            createRevision(-1);
        }

        ctrl.addRevisionFromExistent = function () {
            let formFields = [
                {
                    label: 'Prototype Revision',
                    name: 'prototypeRevision',
                    enum: true,
                    required: true,
                    values: workspace.selection.children.map(revision => revision.title.split(' ')[0]),
                    setFocused: true
                }
            ];
            openCreateRevisionModal(formFields);
        }

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

        function createRevision(prototypeRevision) {
            entaxyCICDService.executeOperation('createRevision',
                [ctrl.storage, ctrl.application, ctrl.version, prototypeRevision])
            .then(result => {
                Entaxy.notificationSuccess(result);
                entaxyCICDService.treeUpdated();
            }).catch(error => {
                Entaxy.notificationError(error);
            });
        }
    }
    EntaxyCICDApplicationController.$inject = ['workspace', '$uibModal', 'entaxyCICDService'];

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