/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2024 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">
                <div class="modal-resources-viewer-container">
                  <div class="modal-resources-viewer-header-container">
                    <entaxy-crumbs root-crumb="$ctrl.protocol" crumbs="$ctrl.crumbs"></entaxy-crumbs>
                    <button type="button" data-toggle="tooltip" title="Create folder"
                            ng-click="$ctrl.addFolder()" ng-if="$ctrl.enableFolderAdding">
                      <span class="pficon pficon-add-circle-o"></span>
                    </button>
                  </div>
                  <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, entaxyResourcesService) {
        'ngInject';

        let ctrl = this;

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

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

            let provider = entaxyResourcesService.getProviderMbean(ctrl.protocol);
            ctrl.providerMBeanName = provider.objectName;

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

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

            let location = ctrl.resolve.location;
            ctrl.useShortUrl = ctrl.resolve.config.useShortUrl;

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

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

        ctrl.changeSelection = function (item) {
            if (!item.error) {
                ctrl.selectedItem = item;
            } else {
                Entaxy.notificationError('Cannot select the resource containing an error');
            }
        }

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

        let clientFolders = [];

        ctrl.addFolder = function () {
            entaxyResourcesService.addFolder(ctrl.items, clientFolders, ctrl.crumbs);
        }

        function updateItems() {
            let path = entaxyResourcesService.getPath(ctrl.crumbs);

            getItems(path).then(originItems => {

                if (ctrl.enableFolderAdding && ctrl.crumbs.length > 0 &&
                        originItems.length == 0 && clientFolders.length == 0) {
                    populateAddedFoldersFromLocation(ctrl.crumbs);
                }

                let items = originItems
                    .concat(entaxyResourcesService.getClientFoldersToAdd(clientFolders, originItems, ctrl.crumbs));

                if (ctrl.filter === 'foldersOnly') {
                    items = items.filter(item => item.isFolder);
                } else 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);
            })
        }

        function populateAddedFoldersFromLocation(originCrumbs) {
            let crumbs = Entaxy.deepCopy(originCrumbs);

            if (crumbs.length > 0) {
                let lastFolderName = crumbs.pop();
                let path = entaxyResourcesService.getPath(crumbs);

                getItems(path).then(result => {
                    let items = JSON.parse(result);

                    if (items.length == 0) {
                        let addedFolder = entaxyResourcesService.createFolder(lastFolderName, crumbs);
                        clientFolders.push(addedFolder);
                        populateAddedFoldersFromLocation(crumbs);
                    } else {
                        if (!items.map(item => item.name).includes(lastFolderName)) {
                            let addedFolder = entaxyResourcesService.createFolder(lastFolderName, crumbs);
                            clientFolders.push(addedFolder);
                        }
                    }
                });
            }
        }

        function getItems(path) {
            return entaxyResourcesService.getResourcesInfo(ctrl.providerMBeanName, path);
        }

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

        ctrl.save = function() {
            if (ctrl.selectedItem) {
                if (!ctrl.selectedItem.isFolder || ctrl.enableFolderSelection) {
                    let path = entaxyResourcesService.getPath(ctrl.crumbs);
                    let folderLocation = getFolderLocation(path);
                    let separator = path.length > 0 ? '/' : '';
                    let location = folderLocation + separator + ctrl.selectedItem.name;
                    ctrl.modalInstance.close(location);
                }
            } else {
                if (ctrl.enableFolderSelection) {
                    let path = entaxyResourcesService.getPath(ctrl.crumbs);
                    let folderLocation = getFolderLocation(path);
                    ctrl.modalInstance.close(folderLocation);
                } else {
                    Entaxy.notificationError('There is no selected resource');
                }
            }
        }

        function getFolderLocation(path) {
            return ctrl.useShortUrl ? ctrl.protocol + ':' + path : 'entaxy-resource://' + ctrl.protocol + '/' + path;
        }
    }
    entaxyResourceViewerModalController.$inject = ['$uibModal', '$scope', 'entaxyResourcesService'];

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