/*-
 * ~~~~~~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('entaxyResources', {
        template:
        `
          <div class="resources-header-container">
            <h2>
              Resources
            </h2>
            <p class="text-muted">{{$ctrl.location}}</p>
            <button type="button" class="btn-clipboard" data-toggle="tooltip" title="Copy location to clipboard" ng-click="$ctrl.copyLocationToClipboard()">
              <span class="fa fa-copy"></span>
            </button>
            <button type="button" data-toggle="tooltip" title="Create folder" ng-click="$ctrl.createFolder()">
              <span class="pficon pficon-add-circle-o"></span>
            </button>
            <button type="button" data-toggle="tooltip" title="Change to list" ng-click="$ctrl.changeView('list')" ng-if="$ctrl.view === 'tiles'">
              <span class="fa fa-list"></span>
            </button>
            <button type="button" data-toggle="tooltip" title="Change to tiles" ng-click="$ctrl.changeView('tiles')" ng-if="$ctrl.view === 'list'">
              <span class="fa fa-th"></span>
            </button>
          </div>

          <entaxy-crumbs root-crumb="$ctrl.protocol" crumbs="$ctrl.crumbs"></entaxy-crumbs>

          <div class="resources-file-drop-zone" entaxy-file-drop ng-model="$ctrl.file" process-fn="$ctrl.upload($ctrl.file)">
            <div class="file-panel-container">
              <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 class="meta-info" resizable r-directions="['left']" ng-if="$ctrl.selectedItem && $ctrl.selectedItem.metadata">
              <uib-tabset active="$ctrl.activeTab" class="meta-tabs">
                <uib-tab ng-repeat="(section, info) in $ctrl.selectedItem.metadata track by $index" heading="{{section}}">
                  <div class="json-formatter">
                    <json-formatter json="info" open="1"></json-formatter>
                  </div>
                </uib-tab>
              </uib-tabset>
            </div>
          </div>
        `,
        controller: entaxyResourcesController
    })
    .name;

    function entaxyResourcesController(workspace, $scope, jolokiaService, operationsService, restService, $timeout, $uibModal) {
        'ngInject';

        let ctrl = this;
        let selectedMbeanName = workspace.getSelectedMBeanName();
        let clientFolders = [];

        ctrl.$onInit = function () {
            ctrl.view = 'list';

            jolokiaService.getAttribute(selectedMbeanName, 'Protocol')
            .then((protocol) => {
                ctrl.protocol = protocol;
                ctrl.crumbs = [];
            });
        }

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

        ctrl.changeView = function (view) {
            ctrl.view = view;
        }

        ctrl.changeSelection = function (item) {
            ctrl.selectedItem = item;
            ctrl.location = getLocation();
            $timeout(function () {
                ctrl.activeTab = 0;
            });
        }

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

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

            operationsService
            .executeOperation(selectedMbeanName, { name: 'getResourcesInfo' }, [ path ])
            .then((result) => {
                let items = JSON.parse(result);
                items.forEach(item => {
                    if (item.metadata) {
                        Object.keys(item.metadata).forEach(section => {
                            item.metadata[section] = JSON.parse(item.metadata[section]);
                        });
                    }
                });
                items = items.concat(getClientFoldersToAdd(items));
                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.copyLocationToClipboard = function() {
            let clipboard = new ClipboardJS('.btn-clipboard', {
                text: (trigger) => ctrl.location
            });
            setTimeout(() => clipboard.destroy(), 1000);
        }

        function getLocation() {
            let separator = getPath().length > 0 ? '/' : '';
            let selectedItemName = ctrl.selectedItem && !ctrl.selectedItem.isFolder ? ctrl.selectedItem.name : '';
            return ctrl.protocol + ':' + getPath() + separator + selectedItemName;
        }

        ctrl.createFolder = function () {

            $uibModal.open({
                component: 'entaxyAddFolderModal',
                resolve: {
                    names: () => ctrl.items.filter((item) => item.isFolder).map((item) => item.name)
                },
                size: 'sm-custom',
                backdrop: 'static',
                windowTopClass: 'modal-top-margin-center-override'
            })
            .result.then(name => {

                let newFolder = {
                    name: name,
                    isFolder: true,
                    crumbs: ctrl.crumbs.map((crumb) => crumb)
                };

                ctrl.items.push(newFolder);
                ctrl.items = ctrl.items.sort(Entaxy.compareBy('name')).sort((a, b) => b.isFolder - a.isFolder);
                clientFolders.push(newFolder);
            });
        }

        function getClientFoldersToAdd(items) {
            let foldersToAdd = [];

            if (clientFolders.length > 0) {

                clientFolders = clientFolders.filter((folder) => {
                    let isSaved = true;
                    if (folder.crumbs.length == ctrl.crumbs.length && (folder.crumbs.length == 0 ||
                            (folder.crumbs.length > 0 && folder.crumbs[folder.crumbs.length - 1] ===
                                    ctrl.crumbs[ctrl.crumbs.length - 1]))) {

                        items.forEach((item) => {
                            if (item.isFolder && item.name === folder.name) {
                                isSaved = false;
                            }
                        });

                        if (isSaved) {
                            foldersToAdd.push(folder);
                        }
                    }
                    return isSaved;
                });
            }

            return foldersToAdd;
        }

        ctrl.upload = function (file) {
            if (!file) {
                return;
            }

            let fd = new FormData();
            fd.append('file', file);
            fd.append('protocol', ctrl.protocol);
            let separator = getPath().length > 0 ? '/' : '';
            fd.append('path', getPath() + separator + file.name);

            restService.post('/cxf/file-upload/upload/resource', fd)
            .then((response) => {
                Core.notification('success', 'File ' + response.data + ' was successfully uploaded.', 3000);
                updateItems();
            })
            .catch((error) => {
                Entaxy.log.error(error);
                Core.notification('danger', 'An error occurred while uploading the file.', 5000);
            });
        }
    }
    entaxyResourcesController.$inject = ['workspace', '$scope', 'jolokiaService', 'operationsService', 'restService', '$timeout', '$uibModal'];

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