import { __esDecorate, __runInitializers } from "tslib";
import { html } from 'lit';
import { DataTable } from '../DataTable.js';
import { property } from 'lit/decorators.js';
import { until } from 'lit/directives/until.js';
import { FolderKind } from '@api-client/core/models/kinds.js';
import { relativeDay } from '../../../lib/time/Conversion.js';
import { fileIcon } from '../../../lib/files/Utils.js';
import services from '../../../services/api_service.js';
let FilesystemDataTable = (() => {
    let _classSuper = DataTable;
    let _user_decorators;
    let _user_initializers = [];
    let _user_extraInitializers = [];
    let _oid_decorators;
    let _oid_initializers = [];
    let _oid_extraInitializers = [];
    return class FilesystemDataTable extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _user_decorators = [property({ type: Object })];
            _oid_decorators = [property({ type: String })];
            __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, _oid_decorators, { kind: "accessor", name: "oid", static: false, private: false, access: { has: obj => "oid" in obj, get: obj => obj.oid, set: (obj, value) => { obj.oid = value; } }, metadata: _metadata }, _oid_initializers, _oid_extraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #user_accessor_storage = __runInitializers(this, _user_initializers, void 0);
        /**
         * The currently logged in user.
         */
        get user() { return this.#user_accessor_storage; }
        set user(value) { this.#user_accessor_storage = value; }
        #oid_accessor_storage = (__runInitializers(this, _user_extraInitializers), __runInitializers(this, _oid_initializers, void 0));
        /**
         * The organization ID these files belongs to.
         * @attribute
         */
        get oid() { return this.#oid_accessor_storage; }
        set oid(value) { this.#oid_accessor_storage = value; }
        handleFileMenuSelect(e) {
            const { item } = e.detail;
            const menu = e.currentTarget;
            const { key } = menu.dataset;
            if (!key) {
                return;
            }
            if (!item.value) {
                return;
            }
            this.dispatchEvent(new CustomEvent('rowaction', { detail: { key, action: item.value } }));
        }
        renderEmpty() {
            return html `<slot name="empty"><p class="empty">You have no files.</p></slot>`;
        }
        renderHeader() {
            return [
                this.renderHeaderCell('Name', 0, { sort: 'name' }),
                this.renderHeaderCell('Owner', 1),
                this.renderHeaderCell('Updated', 2),
                this.renderHeaderCell(html `<span hidden aria-label="Row options">Menu</span>`, 3, { delegateFocus: true }),
            ];
        }
        renderRowValues(item, index) {
            return [
                this.#nameCell(item, index, 0),
                this.#ownerCell(item, index, 1),
                this.#updatedCell(item, index, 2),
                this.renderCell(this.#renderFileMenu(item), index, 3, { classes: ['actions'], delegateFocus: true }),
            ];
        }
        #nameCell(item, row, col) {
            const icon = fileIcon(item);
            const content = html `<ui-icon class="cell-icon" role="presentation">${icon}</ui-icon> ${item.info.name}`;
            return this.renderCell(content, row, col, { classes: ['primary-cell'], isPrimary: true });
        }
        #ownerCell(item, row, col) {
            const opts = {
                classes: ['owner'],
            };
            const { user } = this;
            if (!user) {
                return this.renderCell(html `--`, row, col, opts);
            }
            const owner = item.permissions.find((p) => p.role === 'owner' && p.depth === 0);
            if (!owner) {
                return this.renderCell(html `<span aria-label="Unknown permission">--</span>`, row, col, opts);
            }
            if (owner.granteeId === user.key) {
                return this.renderCell(html `<ui-user-avatar role="presentation" class="avatar body-small" .user="${user}" type="icon"></ui-user-avatar
          ><span aria-label="Owned by me" class="user-label">me</span>`, row, col, opts);
            }
            const content = this.#ownerCellAsync(owner.granteeId);
            const loader = html `<span class="owner-loading">loading...</span>`;
            return this.renderCell(html `${until(content, loader)}`, row, col, opts);
        }
        async #ownerCellAsync(key) {
            if (!key) {
                return html ` <span aria-label="Owned by unknown user">invalid state</span> `;
            }
            // @TODO: Use a context provider and decouple from services singleton
            const cache = await services.get('userCache');
            const user = await cache.getUser(key);
            if (!user) {
                return html ` <span aria-label="Owned by unknown user">unknown</span> `;
            }
            return html `<ui-user-avatar
        role="presentation"
        class="avatar body-small"
        .user="${user}"
        type="icon"
      ></ui-user-avatar
      ><span aria-label="Owned by ${user.name}" class="user-label">${user.name}</span>`;
        }
        #updatedCell(item, row, col) {
            const opts = {
                classes: ['updated'],
            };
            const { lastModified } = item;
            const relative = relativeDay(lastModified.time);
            return this.renderCell(html `<span>${relative}</span>`, row, col, opts);
        }
        #renderFileMenu(item) {
            return item.kind === FolderKind ? this.#renderFolderOptions(item) : this.#renderFileOptions(item);
        }
        #renderFolderOptions(item) {
            const { key } = item;
            return html `
      <ui-icon-button
        data-key="${key}"
        id="anchor-${key}"
        aria-controls="menu-${key}"
        tabindex="-1"
        popoverTarget="menu-${key}"
      >
        <ui-icon>more_vert</ui-icon>
      </ui-icon-button>
      <ui-menu
        class="item-menu"
        popover="auto"
        id="menu-${key}"
        data-key="${key}"
        @select="${this.handleFileMenuSelect}"
      >
        <ui-menu-item value="open">
          <div>Open</div>
          <ui-icon slot="start">folder_open</ui-icon>
        </ui-menu-item>
        <ui-menu-item value="share">
          <div>Share</div>
          <ui-icon slot="start">person_add</ui-icon>
        </ui-menu-item>
        <ui-divider role="separator"></ui-divider>
        <!-- <ui-menu-item value="move">
          <div>Move</div>
          <ui-icon slot="start">drive_file_move</ui-icon>
        </ui-menu-item> -->
        <ui-menu-item value="rename">
          <div>Rename</div>
          <ui-icon slot="start">edit</ui-icon>
        </ui-menu-item>
        <ui-divider role="separator"></ui-divider>
        <ui-menu-item value="delete">
          <div>Delete</div>
          <ui-icon slot="start">delete</ui-icon>
        </ui-menu-item>
      </ui-menu>
    `;
        }
        #renderFileOptions(item) {
            const { key } = item;
            return html `
      <ui-icon-button
        data-key="${key}"
        id="anchor-${key}"
        aria-controls="menu-${key}"
        tabindex="-1"
        popoverTarget="menu-${key}"
      >
        <ui-icon>more_vert</ui-icon>
      </ui-icon-button>
      <ui-menu
        class="item-menu"
        popover="auto"
        id="menu-${key}"
        data-key="${key}"
        @select="${this.handleFileMenuSelect}"
      >
        <ui-menu-item value="open">
          <div>Open</div>
          <ui-icon slot="start">open_in_new</ui-icon>
        </ui-menu-item>
        <ui-menu-item value="share">
          <div>Share</div>
          <ui-icon slot="start">person_add</ui-icon>
        </ui-menu-item>
        <ui-divider role="separator"></ui-divider>
        <!-- <ui-menu-item value="move">
          <div>Move</div>
          <ui-icon slot="start">drive_file_move</ui-icon>
        </ui-menu-item> -->
        <ui-menu-item value="rename">
          <div>Rename</div>
          <ui-icon slot="start">edit</ui-icon>
        </ui-menu-item>
        <ui-divider role="separator"></ui-divider>
        <ui-menu-item value="delete">
          <div>Delete</div>
          <ui-icon slot="start">delete</ui-icon>
        </ui-menu-item>
      </ui-menu>
    `;
        }
        constructor() {
            super(...arguments);
            __runInitializers(this, _oid_extraInitializers);
        }
    };
})();
/**
 * A class that render QuickAPI file system.
 * The user can browse files and perform actions on them.
 *
 * @fires rowaction Dispatched when the user triggers an action on the file.
 *     - `detail`: An object with a `key` and `action` property
 *     - Example: `{ key: 'abc', action: 'delete' }`
 * @attribute sort
 * @attribute sortDirection
 */
export default FilesystemDataTable;
//# sourceMappingURL=FilesystemDataTable.js.map