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

            <entaxy-ci-cd-applications-table type="Application"
                import-from-file="$ctrl.importFromFile" import-from-repository="$ctrl.importFromRepository">
            </entaxy-ci-cd-applications-table>
          </div>
        `,
        controller: EntaxyCICDApplicationsController
    })
    .name;

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

        let ctrl = this;

        const isStorageSelected = EntaxyCICD.isStorage(workspace.selection);

        ctrl.$onInit = function() {
        }

        function getFormFields(isFromRepository) {
            let formFields = [
                {
                    name: 'storage',
                    label: 'Storage',
                    type: 'string',
                    value: isStorageSelected ? workspace.selection.title : undefined,
                    enum: isStorageSelected ? undefined : true,
                    values: isStorageSelected ? undefined : workspace.selection.children.map(child => child.title),
                    required: true,
                    readOnly: isStorageSelected ? true : undefined,
                    setFocused: true
                }
            ];
            if (isFromRepository) {
                formFields.push({
                    name: 'mavenUrl',
                    label: 'Maven Url',
                    type: 'string',
                    required: true
                });
            } else {
                formFields.push({
                    name: 'file',
                    label: 'File',
                    resource: true,
                    required: true
                });
            }
            return formFields;
        }

        ctrl.importFromFile = function () {
            openModalAndProcessResults(false);
        }

        ctrl.importFromRepository = function () {
            openModalAndProcessResults(true);
        }

        function openModalAndProcessResults(isFromRepository) {
            $uibModal.open({
                component: 'entaxyCiCdSimpleFieldsModal',
                resolve: {
                    modalTitle: () => 'Import Application From ' + (isFromRepository ? 'Repository' : 'File'),
                    formFields: () => getFormFields(isFromRepository)
                },
                backdrop: 'static'
            })
            .result.then(args => {
                if (isFromRepository) {
                    processOperation('importFromRepository', args);
                } else {
                    importFromFile(args);
                }
            },
            reason => {
                if (reason && reason !== Entaxy.MODAL_CANCEL_REASON.ESCAPE_KEY_PRESS) {
                    Entaxy.notificationError(reason);
                }
            });
        }

        function importFromFile(args) {
            let file = args[1];
            const reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onloadend = function () {
                const base64String = btoa(reader.result);
                processOperation('importFromBase64String', [args[0], base64String]);
            }
        }

        function processOperation(operationName, properties) {
            entaxyCICDService.executeOperation(operationName, properties)
            .then(result => {
                Entaxy.notificationSuccess(result);
                entaxyCICDService.treeUpdated();
            })
            .catch(error => {
                Entaxy.notificationError(error);
                EntaxyCICD.log.error(error);
            });
        }
    }
    EntaxyCICDApplicationsController.$inject = ['workspace', '$uibModal', 'entaxyCICDService'];

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