import { __esDecorate, __runInitializers } from "tslib";
import { html, LitElement, nothing } from 'lit';
import { property, state } from 'lit/decorators.js';
import { consume } from '@lit/context';
import { FolderKind } from '@api-client/core/models/kinds.js';
import { organizationContext } from '../../../providers/organization.js';
import { userContext } from '../../../providers/user.js';
import { api, folderFilled, schemaModel } from '../../../md/icons/Icons.js';
import '../../../md/icons/ui-icon.js';
import '../../../md/icon-button/ui-icon-button.js';
import '../../../md/button/ui-button.js';
import '../../../md/divider/ui-divider.js';
import '../../../md/menu/ui-menu.js';
import '../../../md/menu/ui-menu-item.js';
import '../ui-breadcrumbs.js';
import '../../data-table/filesystem-table.js';
let QuickApiFilesystem = (() => {
    let _classSuper = LitElement;
    let _source_decorators;
    let _source_initializers = [];
    let _source_extraInitializers = [];
    let _organization_decorators;
    let _organization_initializers = [];
    let _organization_extraInitializers = [];
    let _user_decorators;
    let _user_initializers = [];
    let _user_extraInitializers = [];
    let _files_decorators;
    let _files_initializers = [];
    let _files_extraInitializers = [];
    let _breadcrumbs_decorators;
    let _breadcrumbs_initializers = [];
    let _breadcrumbs_extraInitializers = [];
    let _parent_decorators;
    let _parent_initializers = [];
    let _parent_extraInitializers = [];
    let _selectedItems_decorators;
    let _selectedItems_initializers = [];
    let _selectedItems_extraInitializers = [];
    return class QuickApiFilesystem extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _source_decorators = [property({ type: String })];
            _organization_decorators = [property({ type: Object, attribute: false }), consume({ context: organizationContext, subscribe: true })];
            _user_decorators = [property({ type: Object, attribute: false }), consume({ context: userContext })];
            _files_decorators = [property({ type: Object })];
            _breadcrumbs_decorators = [property({ type: Object })];
            _parent_decorators = [property({ type: Object })];
            _selectedItems_decorators = [state()];
            __esDecorate(this, null, _source_decorators, { kind: "accessor", name: "source", static: false, private: false, access: { has: obj => "source" in obj, get: obj => obj.source, set: (obj, value) => { obj.source = value; } }, metadata: _metadata }, _source_initializers, _source_extraInitializers);
            __esDecorate(this, null, _organization_decorators, { kind: "accessor", name: "organization", static: false, private: false, access: { has: obj => "organization" in obj, get: obj => obj.organization, set: (obj, value) => { obj.organization = value; } }, metadata: _metadata }, _organization_initializers, _organization_extraInitializers);
            __esDecorate(this, null, _user_decorators, { kind: "accessor", name: "user", static: false, private: false, access: { has: obj => "user" in obj, get: obj => obj.user, set: (obj, value) => { obj.user = value; } }, metadata: _metadata }, _user_initializers, _user_extraInitializers);
            __esDecorate(this, null, _files_decorators, { kind: "accessor", name: "files", static: false, private: false, access: { has: obj => "files" in obj, get: obj => obj.files, set: (obj, value) => { obj.files = value; } }, metadata: _metadata }, _files_initializers, _files_extraInitializers);
            __esDecorate(this, null, _breadcrumbs_decorators, { kind: "accessor", name: "breadcrumbs", static: false, private: false, access: { has: obj => "breadcrumbs" in obj, get: obj => obj.breadcrumbs, set: (obj, value) => { obj.breadcrumbs = value; } }, metadata: _metadata }, _breadcrumbs_initializers, _breadcrumbs_extraInitializers);
            __esDecorate(this, null, _parent_decorators, { kind: "accessor", name: "parent", static: false, private: false, access: { has: obj => "parent" in obj, get: obj => obj.parent, set: (obj, value) => { obj.parent = value; } }, metadata: _metadata }, _parent_initializers, _parent_extraInitializers);
            __esDecorate(this, null, _selectedItems_decorators, { kind: "accessor", name: "selectedItems", static: false, private: false, access: { has: obj => "selectedItems" in obj, get: obj => obj.selectedItems, set: (obj, value) => { obj.selectedItems = value; } }, metadata: _metadata }, _selectedItems_initializers, _selectedItems_extraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #source_accessor_storage = __runInitializers(this, _source_initializers, 'own'
        /**
         * The currently selected organization, if any.
         *
         * This property consumes the `organizationContext`.
         */
        );
        /**
         * What kind of files we render.
         * @attribute
         */
        get source() { return this.#source_accessor_storage; }
        set source(value) { this.#source_accessor_storage = value; }
        #organization_accessor_storage = (__runInitializers(this, _source_extraInitializers), __runInitializers(this, _organization_initializers, void 0));
        /**
         * The currently selected organization, if any.
         *
         * This property consumes the `organizationContext`.
         */
        get organization() { return this.#organization_accessor_storage; }
        set organization(value) { this.#organization_accessor_storage = value; }
        #user_accessor_storage = (__runInitializers(this, _organization_extraInitializers), __runInitializers(this, _user_initializers, void 0));
        /**
         * The user object to use with the file system.
         *
         * This property consumes the `userContext`.
         */
        get user() { return this.#user_accessor_storage; }
        set user(value) { this.#user_accessor_storage = value; }
        #files_accessor_storage = (__runInitializers(this, _user_extraInitializers), __runInitializers(this, _files_initializers, void 0));
        /**
         * The list of files to render.
         */
        get files() { return this.#files_accessor_storage; }
        set files(value) { this.#files_accessor_storage = value; }
        #breadcrumbs_accessor_storage = (__runInitializers(this, _files_extraInitializers), __runInitializers(this, _breadcrumbs_initializers, void 0));
        /**
         * The breadcrumbs to render.
         */
        get breadcrumbs() { return this.#breadcrumbs_accessor_storage; }
        set breadcrumbs(value) { this.#breadcrumbs_accessor_storage = value; }
        #parent_accessor_storage = (__runInitializers(this, _breadcrumbs_extraInitializers), __runInitializers(this, _parent_initializers, void 0));
        /**
         * The parent folder of the current view.
         * It is used to compute the permissions for the current view.
         */
        get parent() { return this.#parent_accessor_storage; }
        set parent(value) { this.#parent_accessor_storage = value; }
        #selectedItems_accessor_storage = (__runInitializers(this, _parent_extraInitializers), __runInitializers(this, _selectedItems_initializers, []
        /**
         * Dispatches the `open-folder` event.
         *
         * @param key The key of the folder to open.
         */
        ));
        /**
         * The list of currently selected items.
         */
        get selectedItems() { return this.#selectedItems_accessor_storage; }
        set selectedItems(value) { this.#selectedItems_accessor_storage = value; }
        /**
         * Dispatches the `open-folder` event.
         *
         * @param key The key of the folder to open.
         */
        openFolder(key) {
            this.clearSelection();
            this.dispatchEvent(new CustomEvent('open-folder', {
                detail: { key },
                bubbles: true,
                composed: true,
            }));
        }
        /**
         * Dispatches the `open-file` event.
         *
         * @param file The file to open.
         */
        openFile(file) {
            this.dispatchEvent(new CustomEvent('open-file', {
                detail: { key: file.key, kind: file.kind },
                bubbles: true,
                composed: true,
            }));
        }
        /**
         * Dispatches the `share-files` event.
         *
         * @param files The list of files to share.
         */
        shareFiles(files) {
            this.dispatchEvent(new CustomEvent('share-files', {
                detail: { keys: files.map((file) => file.key) },
            }));
        }
        /**
         * Handler for the item activation event from the data table.
         * Depending on the item kind it opens the folder or the file.
         *
         * @param e The activation event.
         * @throws {Error} When the item kind is unknown.
         */
        itemActivateHandler(e) {
            const item = e.detail;
            const { kind } = item;
            if (kind === FolderKind) {
                this.openFolder(item.key);
            }
            else {
                this.openFile(item);
            }
        }
        /**
         * Handler for the selection event from the data table.
         * Updates the `selectedItems` state.
         *
         * @param e The selection event.
         */
        handleTableSelect(e) {
            this.selectedItems = [...e.detail.selectedItems];
        }
        /**
         * Clears the current selection.
         */
        clearSelection() {
            this.selectedItems = [];
        }
        /**
         * Shares the currently selected files.
         */
        shareSelection() {
            const { selectedItems } = this;
            this.shareFiles(selectedItems);
        }
        /**
         * Removes files from the selection.
         * @param keys The keys of the files to remove from the selection.
         */
        removeFromSelection(keys) {
            const { selectedItems } = this;
            this.selectedItems = selectedItems.filter((item) => !keys.some((key) => key === item.key));
        }
        /**
         * Logic to handle file actions from the data table (e.g. rename, delete, share, open).
         *
         * @param e The file action event.
         */
        handleFileAction(e) {
            const { key } = e.detail;
            const action = e.detail.action;
            switch (action) {
                case 'rename':
                case 'move':
                    this.dispatchEvent(new CustomEvent(`file-${action}`, {
                        detail: { key },
                        bubbles: true,
                        composed: true,
                    }));
                    break;
                case 'delete':
                    this.deleteFiles([key]);
                    break;
                case 'share':
                case 'open': {
                    const item = this.files?.value?.find((item) => item.key === key);
                    if (!item) {
                        return;
                    }
                    if (action === 'share') {
                        this.shareFiles([item]);
                    }
                    else if (action === 'open') {
                        if (item.kind !== FolderKind) {
                            this.openFile(item);
                        }
                        else {
                            this.openFolder(key);
                        }
                    }
                    break;
                }
                default:
                // Unknown action
            }
        }
        /**
         * Handler for the "add file" menu selection.
         * Dispatches the `file-create` event.
         *
         * @param e The menu selection event.
         */
        handleAddMenuSelect(e) {
            const action = e.detail.item.value;
            if (!action || !['folder', 'api', 'domain', 'import'].includes(action)) {
                return;
            }
            this.dispatchEvent(new CustomEvent('file-create', {
                detail: { action },
            }));
        }
        /**
         * Handler for the breadcrumbs navigation event.
         * Opens the folder corresponding to the breadcrumb.
         *
         * @param e The breadcrumb navigation event.
         */
        handleBreadcrumbsNavigate(e) {
            const { key } = e.detail;
            this.openFolder(key);
        }
        /**
         * Deletes the currently selected files.
         */
        handleDeleteSelected() {
            const { selectedItems } = this;
            this.deleteFiles(selectedItems.map((item) => item.key));
        }
        /**
         * Deletes a list of files identified by their keys.
         * Dispatches the `delete-files` event and removes the files from the selection.
         *
         * @param keys The keys of the files to delete.
         */
        async deleteFiles(keys) {
            this.dispatchEvent(new CustomEvent('delete-files', {
                detail: { keys },
            }));
            this.removeFromSelection(keys);
        }
        handleScrollEnd() {
            this.dispatchEvent(new CustomEvent('scroll-end'));
        }
        render() {
            const { selectedItems, files } = this;
            const own = this.source === 'own';
            const ariaLabel = own ? 'Your files' : 'Shared files';
            const content = html `
      <div class="section-header">
        ${selectedItems && selectedItems.length ? this.renderSelection(selectedItems) : this.renderHeader()}
      </div>
      <filesystem-table
        .oid="${this.organization?.key}"
        .user="${this.user}"
        .items="${files}"
        selection="multi"
        active
        ariaLabel="${ariaLabel}"
        .selectedItems="${selectedItems}"
        @activate="${this.itemActivateHandler}"
        @select="${this.handleTableSelect}"
        @rowaction="${this.handleFileAction}"
        @scrollend="${this.handleScrollEnd}"
        class="table"
      >
        ${own
                ? html `<p slot="empty" class="empty">You have no files.</p>`
                : html `<p slot="empty" class="empty">You have no shared files.</p>`}
      </filesystem-table>
    `;
            return content;
        }
        renderSelection(selected) {
            const { length } = selected;
            return html `
      <div class="file-selection-info">
        <ui-icon-button @click="${this.clearSelection}" title="Clear selection" aria-label="Clear selection">
          <ui-icon>close</ui-icon>
        </ui-icon-button>
        <span class="selection-label body-large">${length} selected</span>
        <ui-icon-button
          @click="${this.shareSelection}"
          title="Share selected"
          aria-label="Share selected"
          ?disabled="${length !== 1}"
        >
          <ui-icon>person_add</ui-icon>
        </ui-icon-button>
        <!-- <ui-icon-button>
          <ui-icon>drive_file_move</ui-icon>
        </ui-icon-button> -->
        <ui-icon-button
          @click="${this.handleDeleteSelected}"
          title="Move selected to trash"
          aria-label="Move selected to trash"
        >
          <ui-icon>delete</ui-icon>
        </ui-icon-button>
      </div>
    `;
        }
        renderHeader() {
            return html ` ${this.renderBreadcrumbs()}${this.renderAddFileMenu()} `;
        }
        renderBreadcrumbs() {
            const rootName = this.source === 'own' ? 'Files' : 'Shared';
            return html `
      <div class="breadcrumbs">
        <ui-breadcrumbs
          .breadcrumbs="${this.breadcrumbs}"
          root-name="${rootName}"
          @navigate="${this.handleBreadcrumbsNavigate}"
        ></ui-breadcrumbs>
      </div>
    `;
        }
        renderAddFileMenu() {
            const own = this.source === 'own';
            if (!own) {
                if (this.parent) {
                    const caps = this.parent.value?.capabilities;
                    if (!caps?.canAddChildren) {
                        return nothing;
                    }
                }
                else {
                    return nothing;
                }
            }
            return html `
      <span class="menu-area">
        <ui-button color="filled" id="new-file-anchor" trailingicon popoverTarget="new-file-menu">
          Add
          <ui-icon slot="icon">arrow_drop_down</ui-icon>
        </ui-button>
        <ui-menu id="new-file-menu" popover="auto" @select="${this.handleAddMenuSelect}">
          <ui-menu-item value="folder">
            <div>Folder</div>
            <div slot="supporting-text">A folder for your domains</div>
            <ui-icon slot="start">${folderFilled}</ui-icon>
          </ui-menu-item>
          <ui-menu-item value="domain">
            <div>Domain model</div>
            <div slot="supporting-text">Define your data</div>
            <ui-icon slot="start">${schemaModel}</ui-icon>
          </ui-menu-item>
          <ui-menu-item value="api">
            <div>API</div>
            <div slot="supporting-text">Make data actionable</div>
            <ui-icon slot="start">${api}</ui-icon>
          </ui-menu-item>
          <ui-divider role="separator"></ui-divider>
          <ui-menu-item value="import">
            <div>Import data model</div>
            <div slot="supporting-text">Use well-know domains</div>
            <ui-icon slot="start">download_2</ui-icon>
          </ui-menu-item>
        </ui-menu>
      </span>
    `;
        }
        constructor() {
            super(...arguments);
            __runInitializers(this, _selectedItems_extraInitializers);
        }
    };
})();
/**
 * A component that renders a file system view.
 * It supports listing files, navigating folders, and performing actions on files.
 *
 * The whole logic related to querying files, manipulating them, requesting breadcrumbs
 * or a parent folder is delegated to the parent component or a controller.
 *
 * @fires open-folder - Dispatched when a folder is opened.
 * @fires open-file - Dispatched when a file is opened.
 * @fires share-files - Dispatched when files are shared.
 * @fires file-rename - Dispatched when a file is renamed.
 * @fires file-move - Dispatched when a file is moved.
 * @fires file-create - Dispatched when a file create action is triggered.
 * @fires delete-files - Dispatched when files are deleted.
 * @fires scroll-end - Dispatched when the scroll end on the data table is reached.
 */
export default QuickApiFilesystem;
//# sourceMappingURL=QuickApiFilesystem.js.map