/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2023 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('entaxyModalGroupFields', {
        bindings: {
            groups: '<',
            fields: '<',
            errors: '<',
            mode: '<',
            useFormDirty: '<',
            isFormDirty: '='
        },
        template:
        `
          <div class="modal-group-fields-container">
            <div class="modal-groups-list-container">
              <entaxy-modal-list class="group-list" items="$ctrl.groups" items-label="Group" items-label-plural="Groups"
                selected="$ctrl.selectedGroup" change-selection="$ctrl.change" filter="$ctrl.matchesFilter"></entaxy-modal-list>
            </div>
            <div class="modal-group-fields-form-container">
              <form name="entaxyObjectForm" class="form-horizontal">
                <div class="form-group" ng-class="{'has-error': $ctrl.errors[formField.name]}"
                      ng-repeat="formField in $ctrl.viewedFormFields" ng-if="!formField.isBackRef && !formField.isHidden">
                  <div class="col-sm-4 label-col">
                    <label class="control-label" ng-class="{'required-pf': formField.required}" for="{{formField.name}}">{{formField.label}}</label>
                    <button type="button" class="btn btn-link label-description-popover" popover-placement="auto top-left" popover-trigger="'outsideClick'"
                          uib-popover="{{formField.description}}" ng-if="formField.description">
                      <span class="pficon pficon-help"></span>
                    </button>
                  </div>
                  <div class="col-sm-7">
                    <input type="{{formField.type}}" id="{{formField.name}}" placeholder="{{formField.placeholder}}" ng-class="{'form-control': formField.type !== 'checkbox'}"
                      ng-model="formField.value" ng-readonly="formField.readOnly" ng-disabled="formField.type === 'checkbox' && formField.readOnly"
                      ng-if="!formField.type.startsWith('entaxy.runtime.') && formField.type !== 'xml:route' && (!formField.typeInfo || (formField.typeInfo && formField.typeInfo.type === 'String'))">
                    <entaxy-url-input id="{{formField.name}}" model="formField.value" config="formField.typeInfo"
                      ng-if="formField.type === 'url' && formField.typeInfo" form-controller="entaxyObjectForm"></entaxy-url-input>
                    <entaxy-select type="formField.type" id="{{formField.name}}" filter="formField.filter" model="formField.value"
                      update-parent-fn="$ctrl.updateFieldsAfterSelectionChange" options="formField.options" ng-readonly="formField.readOnly"
                      update-parent="formField.typeInfo ? formField.typeInfo.updateParentFields : false"
                      creation-enabled="formField.typeInfo ? formField.typeInfo.enablePrivateObjectCreation : false"
                      ng-if="formField.type.startsWith('entaxy.runtime.')" form-controller="entaxyObjectForm"></entaxy-select>
                    <entaxy-select-from-enum id="{{formField.name}}" values="formField.typeInfo.values" model="formField.value"
                      readonly="formField.readOnly" is-empty-included="formField.typeInfo.isEmptyIncluded"
                      ng-if="formField.typeInfo && (formField.typeInfo.type === 'enum' || formField.typeInfo.type === 'list')"></entaxy-select-from-enum>
                    <entaxy-xml id="{{formField.name}}" ng-model="formField.value" ng-if="formField.type === 'xml:route'"
                      mode="$ctrl.localMode" disabled="formField.readOnly && !formField.value" form-controller="entaxyObjectForm"></entaxy-xml>
                    <span class="help-block" ng-show="$ctrl.errors[formField.name]">{{$ctrl.errors[formField.name]}}</span>
                  </div>
                </div>
              </form>
            </div>
          </div>
        `,
        controller: entaxyModalGroupFieldsController
    })
    .name;

    function entaxyModalGroupFieldsController(operationsService, $scope) {
        'ngInject';

        var ctrl = this;

        ctrl.$onInit = function() {
            ctrl.localMode = ctrl.mode === Entaxy.MODAL_MODES.ADD ? Entaxy.MODAL_MODES.EDIT : ctrl.mode;

            ctrl.selectedGroup = ctrl.groups[0];

            if (ctrl.useFormDirty) {
                $scope.$watch('entaxyObjectForm.$dirty', function (newValue) {
                    ctrl.isFormDirty = newValue;
                });

                $scope.$watch('$ctrl.isFormDirty', function (newValue) {
                    if ($scope.entaxyObjectForm.$dirty != newValue) {
                        if (newValue) {
                            $scope.entaxyObjectForm.$setDirty();
                        } else {
                            $scope.entaxyObjectForm.$setPristine();
                        }
                    }
                });
            }
        }

        ctrl.$onChanges = function(changes) {
            if (changes.errors && changes.errors.currentValue) {
                let errorKeys = Object.keys(changes.errors.currentValue);
                if (errorKeys.length > 0) {
                    let errorField = ctrl.fields.find(field => field.name === errorKeys[0]);
                    ctrl.selectedGroup = ctrl.groups.find(group => group.name === errorField.group);
                }
            }
        }

        ctrl.change = function(group) {
            ctrl.viewedFormFields = ctrl.fields.filter((formField) => formField.group === group.name);
            ctrl.selectedGroup = group;
        }

        ctrl.matchesFilter = function(group, filter) {
            let match = false;

            _.forEach(ctrl.fields.filter((formField) => formField.group === group.name), (field) => {
                if (field.tag && field.tag.length !== 0) {
                    if (field.tag.toLowerCase().match(filter.value.toLowerCase()) !== null) {
                        match = true;
                        return match;
                    }
                }
            });
            match = group.displayName.toLowerCase().match(filter.value.toLowerCase()) !== null;

            return match;
        };

        ctrl.updateFieldsAfterSelectionChange = function (oldItem, newItem, itemType) {

            if (oldItem) {
                changeFieldsFromSelected(oldItem, itemType, true);
            }

            changeFieldsFromSelected(newItem, itemType, false);
        }

        function changeFieldsFromSelected(item, itemType, toDefaults) {
            if (item.mbeanName) {
                operationsService
                .executeOperation(item.mbeanName, { name: 'get' + itemType + 'Config' }, [ item.name ])
                .then(result => {
                    let itemInfo = JSON.parse(result);
                    let properties = itemInfo.properties;

                    changeFieldsValuesFromProperties(properties, toDefaults);

                }).catch(error => {
                    Core.notification('danger', error, 5000);
                    Entaxy.log.error(error);
                });
            } else if (item.value) {
                let properties = item.value.properties;

                changeFieldsValuesFromProperties(properties, toDefaults);
            }
        }

        function changeFieldsValuesFromProperties(properties, toDefaults) {
            if (properties && Object.keys(properties).length > 0) {
                let keys = Object.keys(properties);

                keys.forEach(key => {
                    let field = ctrl.fields.find(field => field.name === key);
                    if (field && !field.isHidden) {
                        field.value = toDefaults ? field.defaultValue : properties[key];
                    }
                });
            }
        }
    }
    entaxyModalGroupFieldsController.$inject = ['operationsService', '$scope'];

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