/*-
 * ~~~~~~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('entaxyProfileDiagramPalette', {
            template:
            `
              <div class="profile-diagram-palette">
                <div class="profile-diagram-palette-title">
                  <span>
                    Connectors Palette
                  </span>
                  <input type="search" class="form-control" placeholder="Search..." ng-model="$ctrl.filter"
                        ng-keypress="$ctrl.onValueKeyPress($event)">
                </div>
                <uib-accordion>
                  <div class="profile-diagram-palette-group-container">
                    <entaxy-profile-diagram-palette-group heading="---IN---" is-open="$ctrl.isInGroupOpened"
                          factories="$ctrl.viewedInFactories"></entaxy-profile-diagram-palette-group>
                    <entaxy-profile-diagram-palette-group heading="---OUT---" is-open="$ctrl.isOutGroupOpened"
                          factories="$ctrl.viewedOutFactories"></entaxy-profile-diagram-palette-group>
                  </div>
                </uib-accordion>
              </div>
            `,
            controller: entaxyProfileDiagramPaletteController
        })
        .component('entaxyProfileDiagramPaletteGroup', {
            bindings: {
                heading: '@',
                isOpen: '=',
                factories: '<'
            },
            template:
            `
              <div uib-accordion-group class="panel-default" heading="{{$ctrl.heading}}" is-open="$ctrl.isOpen">
                <div class="profile-diagram-palette-items-container">
                  <div draggable class="profile-diagram-palette-item" id="{{factory.name}}"
                        ng-repeat="factory in $ctrl.factories"
                        data-toggle="tooltip" title="{{factory.description}}">
                    <span>{{ factory.displayName }}</span>
                  </div>
                </div>
              </div>
            `
        })
        .name;

    function entaxyProfileDiagramPaletteController($scope, jolokia, entaxyService, $cookies) {
        'ngInject';

        let ctrl = this;

        ctrl.$onInit = function () {
            populateConnectorFactories();

            ctrl.isInGroupOpened = $cookies.getObject('diagram-palette-in-group-opened');
            ctrl.isOutGroupOpened = $cookies.getObject('diagram-palette-out-group-opened');
        }

        function populateConnectorFactories() {
            let factories = [];

            let factoryFolder = entaxyService.getFolderByTitle(Entaxy.RUNTIME_TYPE.CONNECTOR);

            if (factoryFolder && factoryFolder.children) {
                factoryFolder.children.forEach((child) => {
                    let attributes = jolokia.getAttribute(child.objectName);

                    if (!attributes.Abstract) {
                        factories.push({
                            name: attributes.Id,
                            displayName: attributes.ShortName ? attributes.ShortName : attributes.Id,
                            mbeanName: child.objectName,
                            description: attributes.Description ?
                                attributes.Description.replace(/(<([^>]+)>)/ig, '') :
                                'There is no description for this factory.',
                            direction: attributes.TypeInfo.direction,
                            label: attributes.Label
                        });
                    }
                });
            }

            ctrl.inFactories = factories.filter(factory => factory.direction === 'in')
                .sort(Entaxy.compareBy('displayName'));
            ctrl.outFactories = factories.filter(factory => factory.direction === 'out')
                .sort(Entaxy.compareBy('displayName'));
            ctrl.viewedInFactories = ctrl.inFactories;
            ctrl.viewedOutFactories = ctrl.outFactories;
        }

        $scope.$watch('$ctrl.isInGroupOpened', function (newValue) {
            $cookies.putObject('diagram-palette-in-group-opened', newValue);
        });

        $scope.$watch('$ctrl.isOutGroupOpened', function (newValue) {
            $cookies.putObject('diagram-palette-out-group-opened', newValue);
        });

        ctrl.onValueKeyPress = function (keyEvent) {
            if (keyEvent.key === 'Enter') {
                keyEvent.stopPropagation();
                keyEvent.preventDefault();

                if (ctrl.filter && ctrl.filter.length > 0) {
                    filter(ctrl.filter);
                } else {
                    ctrl.viewedInFactories = ctrl.inFactories;
                    ctrl.viewedOutFactories = ctrl.outFactories;
                }
            }
        }

        function filter(filter) {
            ctrl.viewedInFactories = ctrl.inFactories.filter(factory => matchesFilter(factory, filter));
            ctrl.viewedOutFactories = ctrl.outFactories.filter(factory => matchesFilter(factory, filter));
        }

        function matchesFilter(factory, filter) {
            let match = false;
            if (factory.displayName.toLowerCase().match(filter.toLowerCase()) !== null &&
                    (factory.label && factory.label.toLowerCase().match(filter.toLowerCase()) !== null)) {
                match = true
            }
            return match;
        }
    }

    entaxyProfileDiagramPaletteController.$inject = ['$scope', 'jolokia', 'entaxyService', '$cookies'];

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