/*-
 * ~~~~~~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('entaxyModalList', {
        bindings: {
            items: '<',
            itemsLabel: '@',
            itemsLabelPlural: '@',
            enableDblClick: '<',
            selected: '<',
            changeSelection: '<',
            filter: '<'
        },
        template:
        `
          <div class="modal-list-container">
            <div class="modal-list-toolbar-container">
              <pf-toolbar class="entaxy-toolbar" config="$ctrl.toolbarConfig"></pf-toolbar>
            </div>
            <div class="modal-list-list-container">
              <pf-list-view class="entaxy-list" items="$ctrl.viewedItems" config="$ctrl.listConfig">
                <div class="list-view-pf-description">
                  <div class="list-group-item-heading">
                    {{item.displayName}}
                  </div>
                </div>
                <div class="list-view-pf-additional-info" ng-if="item.additionalInfo">
                  <div class="list-view-pf-additional-info-item" ng-repeat="info in item.additionalInfo">
                    {{info}}
                  </div>
                </div>
              </pf-list-view>
            </div>
          </div>
        `,
        controller: entaxyModalListController
    })
    .name;

    function entaxyModalListController($scope) {
        'ngInject';

        let ctrl = this;

        ctrl.$onInit = function() {
            ctrl.viewedItems = ctrl.items;
            ctrl.toolbarConfig.filterConfig.itemsLabel = ctrl.itemsLabel ? ctrl.itemsLabel : 'Result';
            ctrl.toolbarConfig.filterConfig.itemsLabelPlural = ctrl.itemsLabelPlural ? ctrl.itemsLabelPlural : 'Results';
            ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedItems.length;

            if (ctrl.selected) {
                ctrl.listConfig.selectedItems = [ ctrl.selected ];
                changeSelection();
            }
        }

        $scope.$watch('$ctrl.selected', function (newValue, oldValue) {
            if (oldValue && newValue && newValue.name !== oldValue.name) {
                ctrl.listConfig.selectedItems = [ ctrl.selected ];
                changeSelection();
            }
        });

        $scope.$watch('$ctrl.items', function (newValue, oldValue) {
            if (newValue !== oldValue) {
                ctrl.viewedItems = ctrl.items;
                ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedItems.length;
            }
        });

        ctrl.toolbarConfig = {
            filterConfig: {
                fields: [
                    {
                        id: 'displayName',
                        title: 'Name',
                        placeholder: 'Search...',
                        filterType: 'text'
                    }
                ],
                appliedFilters: [],
                onFilterChange: filterChange
            },
            actionsConfig: {}
        };

        function filterChange(filters) {
            applyFilters(filters);
            ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedItems.length;
        };

        function applyFilters(filters) {
            ctrl.viewedItems = [];
            if (filters && filters.length > 0) {
                ctrl.items.forEach(function (item) {
                    if (matchesFilters(item, filters)) {
                        ctrl.viewedItems.push(item);
                    }
                });
            } else {
                ctrl.viewedItems = ctrl.items;
            }
        };

        function matchesFilters(item, filters) {
            var matches = true;
            filters.forEach(function(filter) {
                if (!matchesFilter(item, filter)) {
                    matches = false;
                    return matches;
                }
            });
            return matches;
        };

        function matchesFilter(item, filter) {
            if (ctrl.filter) {
                return ctrl.filter(item, filter);
            } else {
                var match = true;
                if (filter.id === 'displayName') {
                    match = item.displayName.toLowerCase().match(filter.value.toLowerCase()) !== null;
                }
                return match;
            }
        };

        ctrl.listConfig = {
            selectionMatchProp: 'name',
            selectItems: true,
            showSelectBox: false,
            onSelectionChange: changeSelection,
            dlbClick: true,
            onDblClick: (item) => changeSelectionOnDblClick(item)
        }

        function changeSelection() {
            if (ctrl.selected && !ctrl.listConfig.selectedItems[0]) {
                ctrl.listConfig.selectedItems[0] = ctrl.selected;
            } else {
                ctrl.selected = ctrl.listConfig.selectedItems[0];
                ctrl.changeSelection(ctrl.listConfig.selectedItems[0], false);
            }
        }

        function changeSelectionOnDblClick(item) {
            if (ctrl.enableDblClick === true) {
                ctrl.changeSelection(item, true);
            }
        }
    }
    entaxyModalListController.$inject = ['$scope'];

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