/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-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 Entaxy;
(function (Entaxy) {
    Entaxy._module.component('entaxyAddConnectorModal', {
        bindings: {
            modalInstance: '<',
            resolve: '<'
        },
        template:
        `
        <div class="entaxy-modal-container">
          <div class="modal-header">
            <button type="button" class="close" aria-label="Close" ng-click="$ctrl.cancel()">
              <span class="pficon pficon-close" aria-hidden="true"></span>
            </button>
            <h4 class="modal-title">{{$ctrl.modalTitle}}</h4>
          </div>
          <div ng-if="$ctrl.step1 && $ctrl.profiles">
            <div class="modal-body-header">
              <h2>Choose profile to attach connector to</h2>
            </div>
            <div class="modal-body" style="height:433px; max-height:433px">
                <entaxy-modal-list items="$ctrl.profiles" selected="$ctrl.selectedProfile"
                      change-selection="$ctrl.changeProfileSelection" enable-dbl-click="true"></entaxy-modal-list>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" ng-click="$ctrl.next()"
                  ng-disabled="!$ctrl.selectedProfile">Next</button>
            </div>
          </div>
          <div ng-if="$ctrl.step2">
            <div class="modal-body-header">
              <h2>Choose connector template</h2>
            </div>
            <div class="modal-body" style="height:433px; max-height:433px">
                <entaxy-modal-list items="$ctrl.templates" selected="$ctrl.selectedTemplate"
                      change-selection="$ctrl.changeTemplateSelection" enable-dbl-click="true"></entaxy-modal-list>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" ng-click="$ctrl.back()" ng-if="$ctrl.profiles">Back</button>
              <button type="button" class="btn btn-default" ng-click="$ctrl.next()"
                  ng-disabled="!$ctrl.selectedTemplate">Next</button>
            </div>
          </div>
          <form name="connectorForm" class="form-horizontal" ng-if="$ctrl.step3" ng-submit="$ctrl.saveConnector($ctrl.formFields)">
            <div class="modal-body" style="height:503px; max-height:503px;">
              <div class="modal-body-header">
                <h2>Fill in connector template parameters</h2>
              </div>
              <div class="form-group" ng-class="{'has-error': $ctrl.errors[formField.name]}"
                    ng-repeat="formField in $ctrl.formFields" style="margin:15px;">
                <label class="col-sm-3 control-label" ng-class="{'required-pf': formField.isRequired}" for="{{formField.name}}">{{formField.label}}</label>
                <div class="col-sm-8">
                  <input type="{{formField.type}}" id="{{formField.name}}" ng-class="{'form-control': formField.type !== 'checkbox'}"
                        ng-model="formField.value" ng-readonly="formField.isReadOnly" ng-if="!formField.typeInfo">
                  <span class="help-block" ng-show="$ctrl.errors[formField.name]">{{$ctrl.errors[formField.name]}}</span>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" ng-click="$ctrl.back()">Back</button>
              <button type="submit" class="btn btn-primary">Add</button>
            </div>
          </form>
        </div>
        `,
        controller: EntaxyAddConnectorModalController
    })
    .name;

    function EntaxyAddConnectorModalController(workspace, jolokia) {
        'ngInject';

        var ctrl = this;

        ctrl.$onInit = function() {

            let templates = Entaxy.getConnectorTemplates();
            ctrl.templates = templates.map(template => { return { name: template, displayName: template }});

            ctrl.profiles = ctrl.resolve.profiles;

            if (ctrl.profiles) {
                ctrl.step1 = true;
                ctrl.step2 = false;
                ctrl.step3 = false;
            } else {
                ctrl.step1 = false;
                ctrl.step2 = true;
                ctrl.step3 = false;
            }

            ctrl.modalTitle = ctrl.resolve.profileName ?
                'Add Legacy Connector to ' + ctrl.resolve.profileName : 'Add Legacy Connector';
        }

        ctrl.changeProfileSelection = function(item, isDblClicked) {
            ctrl.selectedProfile = item;
            if (isDblClicked) {
                ctrl.next();
            }
        }

        ctrl.changeTemplateSelection = function(item, isDblClicked) {
            ctrl.selectedTemplate = item;
            if (isDblClicked) {
                ctrl.next();
            }
        }

        ctrl.next = function() {
            if (ctrl.step1 === true) {
                ctrl.step1 = false;
                ctrl.step2 = true;
            } else if (ctrl.step2 === true) {
                ctrl.step2 = false;
                ctrl.step3 = true;
            }

            if (ctrl.step3 === true) {
                defineFormFields();
            }
        }

        function defineFormFields() {
            if (!ctrl.formFields || ctrl.selectedTemplate.name !== ctrl.formFields[0].value) {
                ctrl.formFields = Entaxy.getConnectorTemplateParams(ctrl.selectedTemplate.name);

                ctrl.formFields.unshift({
                    label: 'templateName',
                    displayName: 'Template Name',
                    type: 'java.lang.String',
                    helpText: null,
                    value: ctrl.selectedTemplate.name,
                    isReadOnly: true
                });
                ctrl.formFields.forEach(formField => {
                    formField.name = formField.label;
                    if (formField.displayName) {
                        formField.label = formField.displayName;
                    }
                    formField.type = Entaxy.convertToHtmlInputType(formField.type);
                });
            }
        }

        ctrl.back = function() {
            if (ctrl.step2 === true) {
                ctrl.step1 = true;
                ctrl.step2 = false;
            } else if (ctrl.step3 === true) {
                ctrl.step2 = true;
                ctrl.step3 = false;
            }
        }

        ctrl.cancel = function() {
            ctrl.modalInstance.dismiss();
        }

        ctrl.saveConnector = function(fields) {
            ctrl.errors = validateFields(fields);

            if (Object.keys(ctrl.errors).length === 0) {
                let connectorArgs = {
                    profile: ctrl.selectedProfile,
                    connectorTemplateName: ctrl.formFields.shift().value,
                    connectorFields: ctrl.formFields.map(formField => { return { label: formField.name, value: formField.value }; })
                };

                ctrl.modalInstance.close(connectorArgs);
            }
        }

        function validateFields(fields) {
            let errors = {};

            _.forEach(fields, (field) => {
                if (field.isRequired &&
                    (!field.value || (field.type !== 'checkbox' ? field.value.toString().trim().length === 0 : false))) {
                    errors[field.name] = Entaxy.ERROR_MESSAGE.EMPTY;
                }
            });

            return errors;
        }
    }
    EntaxyAddConnectorModalController.$inject = ['workspace', 'jolokia'];

})(Entaxy || (Entaxy = {}));
