/*-
 * ~~~~~~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('entaxyResourceViewerModal', {
        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 class="modal-body-without-header" style="margin-top: 0;">
                <div class="modal-resources-viewer-container">
                  <entaxy-crumbs root-crumb="$ctrl.protocol" crumbs="$ctrl.crumbs"></entaxy-crumbs>
                  <entaxy-file-panel items="$ctrl.items" selected-item="$ctrl.selectedItem" view="$ctrl.view"
                        change-selection-fn="$ctrl.changeSelection" open-fn="$ctrl.open"></entaxy-file-panel>
                </div>
              </div>
              <div class="modal-footer">
                <button type="submit" class="btn btn-primary" ng-click="$ctrl.save()">Select</button>
              </div>
          </div>
        `,
        controller: entaxyResourceViewerModalController
    })
    .name;

    function entaxyResourceViewerModalController($uibModal, $scope, workspace, operationsService, entaxyService) {
        'ngInject';

        let ctrl = this;
        let entaxyJmxDomain = localStorage['entaxyJmxDomain'] || "ru.entaxy.esb";

        ctrl.$onInit = function() {
            ctrl.modalTitle = 'Select Resources';

            ctrl.view = 'tiles';
            ctrl.protocol = ctrl.resolve.config.resourceProvider;

            let provider = entaxyService.getDomainFolder().findDescendant(child => {
                let childObjectName = child.objectName;

                if (childObjectName && childObjectName.startsWith(entaxyJmxDomain) && childObjectName.endsWith('provider=' + ctrl.protocol)) {
                    return child;
                }
            });
            ctrl.providerMBeanName = provider.objectName;

            ctrl.filter = ctrl.resolve.config.filter;

            ctrl.enableFolderSelection = ctrl.resolve.config.target === 'folder' ? true : false;

            let location = ctrl.resolve.location;

            if (location && location.includes(':')) {
                let path = location.split(':')[1];
                let splitPath = path.split('/');
                if (!ctrl.enableFolderSelection) {
                    splitPath.pop();
                }
                // todo else check if the last item in path is folder or not
                ctrl.crumbs = splitPath;
            } else {
                ctrl.crumbs = [];
            }
        }

        $scope.$watchCollection('$ctrl.crumbs', function(newValue, oldValue) {
            ctrl.selectedItem = null;
            updateItems();
        })

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

        ctrl.open = function (item) {
            if (item.isFolder === true) {
                ctrl.crumbs.push(item.name);
            } else {
                ctrl.changeSelection(item);
                ctrl.save();
            }
        }

        function updateItems() {
            let path = getPath();

            operationsService
            .executeOperation(ctrl.providerMBeanName, { name: 'getResourcesInfo' }, [ path ])
            .then((result) => {
                let items = JSON.parse(result);

                if (Array.isArray(ctrl.filter) && ctrl.filter.length > 0) {
                    items = items.filter(item => {
                        let match = false;
                        if (item.isFolder) {
                            return true;
                        }
                        ctrl.filter.forEach(filter => {
                            if (filter.startsWith('*') && item.name.endsWith(filter.substring(1, filter.length))) {
                                match = true;
                            }
                        });
                        return match;
                    });
                } else if (ctrl.filter && ctrl.filter.startsWith('*')) {
                    items = items.filter(item => item.isFolder || item.name.endsWith(ctrl.filter.substring(1, ctrl.filter.length)));
                }
                ctrl.items = items.sort(Entaxy.compareBy('name')).sort((a, b) => b.isFolder - a.isFolder);
            })
            .catch((error) => {
                Entaxy.log.error(error);
                Core.notification('danger', 'An error occurred while getting resources.', 5000);
            })
        }

        function getPath() {
            let path = '';
            if (ctrl.crumbs && ctrl.crumbs.length > 0) {
                path = ctrl.crumbs.join('/');
            }
            return path;
        }

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

        ctrl.save = function() {
            if ((!ctrl.enableFolderSelection && !ctrl.selectedItem.isFolder) || ctrl.enableFolderSelection) {
                let separator = getPath().length > 0 ? '/' : '';
                let location = ctrl.protocol + ':' + getPath() + separator + ctrl.selectedItem.name;
                ctrl.modalInstance.close(location);
            }
        }
    }
    entaxyResourceViewerModalController.$inject = ['$uibModal', '$scope', 'workspace', 'operationsService', 'entaxyService'];

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