/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
var Entaxy;
(function (Entaxy) {
    Entaxy._module.component('entaxyModal', {
        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">
              <div class="modal-body-header">
                <h2>{{$ctrl.firstStepTitle}}</h2>
              </div>
              <div class="modal-body">
                <entaxy-modal-list items="$ctrl.templates" selected="$ctrl.selectedItem"
                      change-selection="$ctrl.changeSelection"></entaxy-modal-list>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" ng-click="$ctrl.next()"
                      ng-disabled="!$ctrl.selectedItem">Next</button>
              </div>
            </div>

            <div ng-if="$ctrl.step2">
              <div class="modal-body-header">
                <h2>{{$ctrl.secondStepTitle}}</h2>
              </div>
              <div class="modal-body">
                <entaxy-modal-group-fields groups="$ctrl.groups" fields="$ctrl.formFields"
                      errors="$ctrl.errors"></entaxy-modal-group-fields>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" ng-if="$ctrl.hasSteps" ng-click="$ctrl.back()">Back</button>
                <button type="submit" class="btn btn-primary" ng-click="$ctrl.save($ctrl.formFields)">Add</button>
              </div>
            <div>
          </div>
        `,
        controller: entaxyModalController
    })
    .name;

    function entaxyModalController(workspace, operationsService) {
        'ngInject';

        var ctrl = this;

        ctrl.$onInit = function() {

            ctrl.modalTitle = ctrl.resolve.modalTitle ? ctrl.resolve.modalTitle : 'Modal'; // fixme do required
            ctrl.firstStepTitle = ctrl.resolve.firstStepTitle ? ctrl.resolve.firstStepTitle : ctrl.modalTitle;
            ctrl.secondStepTitle = ctrl.resolve.secondStepTitle ? ctrl.resolve.secondStepTitle : ctrl.modalTitle;

            ctrl.templates = ctrl.resolve.templates ? ctrl.resolve.templates : null;

            // fixme it was only if (ctrl.templates)
            if (ctrl.templates && ctrl.templates.length !== 0) { // fixme or maybe if ctrl.templates.length === 1 and then factoryId = ctrl.templates[0]
                if (ctrl.templates.length > 1) {
                    ctrl.step1 = true;
                    ctrl.step2 = false;
                    ctrl.hasSteps = true;
                } else if (ctrl.templates.length === 1) {
                    ctrl.hasSteps = false;
                    ctrl.next();
                }
            } else {
                ctrl.cancel('Templates are not found');
            }
        }

        ctrl.next = function() {
//            ctrl.step1 = false;
//            ctrl.step2 = true;

            // fixme this if perhaps is needed only if hasSteps is true
            if (!ctrl.formFields || ctrl.selectedItem.name !== ctrl.formFields[0].value) {

                ctrl.formFields = [];

                ctrl.formFields.push({
                    label: 'factoryId',
                    type: 'java.lang.String',
                    helpText: null,
                    value: ctrl.hasSteps ? ctrl.selectedItem.name : ctrl.templates[0].name,
                    readOnly: true,
                    required: true,
                    group: 'general'
                });

                let mbeanName = ctrl.hasSteps ? ctrl.selectedItem.mbeanName : ctrl.templates[0].mbeanName;

                operationsService.executeOperation(mbeanName, { name: 'getFields' }, [ 'init' ])
                .then((response) => {

                    let groups = new Set();
                    groups.add('general');

                    _.forEach(JSON.parse(response), (field) => {
                        let formField = {
                            label: field.displayName ? field.displayName : field.name,
                            type: field.type,
                            description: field.description,
                            immutable: field.immutable,
                            required: field.required,
                            value: field.defaultValue,
                            conditional: field.conditional,
                            isRef: field.isRef,
                            isBackRef: field.isBackRef,
                            group: field.group ? field.group : 'general',
//                            tag: field.label
                        };
                        ctrl.formFields.push(formField);
                        groups.add(formField.group);
                    });

                    ctrl.formFields.forEach(formField => formField.type = Entaxy.convertToHtmlInputType(formField.type));

                    ctrl.groups = Array.from(groups).map((group) => { return { name: group }; });

                    ctrl.step1 = false;
                    ctrl.step2 = true;
                });
            } else {
                ctrl.step1 = false;
                ctrl.step2 = true;
            }
        }

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

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

        ctrl.changeSelection = function(item) {
            ctrl.selectedItem = item;
        }

        ctrl.save = function(item) {
            // fixme maybe forEach here
            ctrl.errors = validateFields(ctrl.formFields);

            if (Object.keys(ctrl.errors).length === 0) {
                let factoryIdName = ctrl.formFields.shift().value;

                args = {
                    factoryId: ctrl.templates.find((template) => template.name === factoryIdName),
                    fields: ctrl.formFields.map(formField => { return { label: formField.label, value : (formField.nestedValue ? formField.nestedValue : formField.value) }; })
                };

                ctrl.modalInstance.close(args);
            }
        }

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

            _.forEach(fields, (field) => {
                if (field.required && !field.isBackRef) {
                    if (!field.value || (field.type !== 'checkbox' ? field.value.trim().length === 0 : false)) {
                        errors[field.label] = 'Please fill out this field';
                    }
                }
            });

            return errors;
        }
    }
    entaxyModalController.$inject = ['workspace', 'operationsService'];

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