import { HttpProject, Project, Folder, ProjectKind, FolderKind, EventUtils, DataNamespace, DataFile, DataFileKind, } from "@api-client/core/build/browser.js";
import { html, nothing } from "lit";
import { join } from "lit/directives/join.js";
import { map } from "lit/directives/map.js";
import { until } from 'lit/directives/until.js';
import { DataTable } from "../../../ui/table/DataTable.js";
import { NavigationEvents } from "../../../events/NavigationEvents.js";
import { navigate } from "../../../lib/route.js";
import { DataImportProcessor } from "../../../http-client/store/DataImportProcessor.js";
import { SnackNotifications } from "../../../ui/notification/SnackNotifications.js";
import UserCache from '../../../store/UserCache.js';
import AppInfo from '../AppInfo.js';
import { fileIcon } from "../../../elements/store/FilesLib.js";
import { FileSystem } from "../../../store/FileSystem.js";
import '@github/relative-time-element';
import '../../../define/ui/ui-list.js';
import '../../../define/ui/ui-list-item.js';
import '../../../define/ui/ui-dropdown-list.js';
import '../../../define/ui/ui-icon.js';
import '../../../define/ui/ui-icon-button.js';
import '../../../define/ui/ui-button.js';
import '../../../define/ui/ui-divider.js';
import '../../../define/ui/ui-text-field.js';
import '../../../define/dialog/rename-dialog.js';
import '../../../define/store/share-file.js';
var ImportState;
(function (ImportState) {
    ImportState[ImportState["Analyzing"] = 0] = "Analyzing";
    ImportState[ImportState["Analyzed"] = 1] = "Analyzed";
    ImportState[ImportState["Importing"] = 2] = "Importing";
    ImportState[ImportState["Done"] = 3] = "Done";
    ImportState[ImportState["Error"] = 4] = "Error";
})(ImportState || (ImportState = {}));
/**
 * A class that specializes in rendering the list of files in HTTP Client.
 */
export class FilesPage {
    constructor(screen) {
        this.screen = screen;
        this.fs = new FileSystem();
        this.dt = new DataTable(() => this.fs.files, { ariaLabel: 'Your files', active: true, selection: 'single' });
        this.createProjectHandler = this.createProjectHandler.bind(this);
        this.createFolderHandler = this.createFolderHandler.bind(this);
        this.createSelectHandler = this.createSelectHandler.bind(this);
        this.pageOptionsSelectHandler = this.pageOptionsSelectHandler.bind(this);
        this.importHandler = this.importHandler.bind(this);
        this.cancelImportDialog = this.cancelImportDialog.bind(this);
        this.cancelCreateProjectDialog = this.cancelCreateProjectDialog.bind(this);
        this.cancelCreateFolderDialog = this.cancelCreateFolderDialog.bind(this);
        this.handleFileOptionSelect = this.handleFileOptionSelect.bind(this);
        this.cancelCreateSchemaDialog = this.cancelCreateSchemaDialog.bind(this);
        this.createSchemaHandler = this.createSchemaHandler.bind(this);
        this.handleSelectedShare = this.handleSelectedShare.bind(this);
        this.handleSelectedTrash = this.handleSelectedTrash.bind(this);
        this.dt.addEventListener('empty', this.renderEmptyTable.bind(this));
        this.dt.addEventListener('header', this.renderTableHeader.bind(this));
        this.dt.addEventListener('item', this.renderTableItem.bind(this));
        this.dt.addEventListener('activate', this.itemActivateHandler.bind(this));
        this.dt.addEventListener('render', this.handleTableRender.bind(this));
        this.dt.addEventListener('select', this.handleTableSelect.bind(this));
        this.dt.addEventListener('scrollend', this.handleTableScrollEnd.bind(this));
        this.fs.observe();
        this.fs.addEventListener('change', () => this.screen.render());
        this.fs.addEventListener('error', (e) => {
            const event = e;
            this.errorMessage = event.detail;
        });
        this.fs.addEventListener('querycomplete', () => {
            document.body.dispatchEvent(new Event('querycomplete', { bubbles: true }));
        });
    }
    async refresh() {
        this.fs.resetList();
        this.screen.render();
        await this.fs.queryPage();
        await this.fs.queryBreadcrumbs();
    }
    cancelCreateProjectDialog() {
        this.screen.closeDialog('createProjectDialog');
    }
    cancelCreateFolderDialog() {
        this.screen.closeDialog('createFolderDialog');
    }
    cancelImportDialog() {
        this.screen.closeDialog('importProjectDialog');
    }
    cancelCreateSchemaDialog() {
        this.screen.closeDialog('createSchemaDialog');
    }
    createProjectHandler(e) {
        const form = e.target;
        const input = form.querySelector('ui-text-field');
        if (!input) {
            return;
        }
        const { submitter } = e;
        if (!submitter) {
            return;
        }
        const button = submitter; // or equivalent
        if (button.value !== 'submit') {
            return;
        }
        const { value } = input;
        input.value = '';
        this.addProject(value);
    }
    createFolderHandler(e) {
        const form = e.target;
        const input = form.querySelector('ui-text-field');
        if (!input) {
            return;
        }
        const { submitter } = e;
        if (!submitter) {
            return;
        }
        const button = submitter; // or equivalent
        if (button.value !== 'submit') {
            return;
        }
        const { value } = input;
        input.value = '';
        this.addFolder(value);
    }
    createSchemaHandler(e) {
        const form = e.target;
        const input = form.querySelector('ui-text-field');
        if (!input) {
            return;
        }
        const { submitter } = e;
        if (!submitter) {
            return;
        }
        const button = submitter; // or equivalent
        if (button.value !== 'submit') {
            return;
        }
        const { value } = input;
        input.value = '';
        this.addSchema(value);
    }
    async addProject(name) {
        const { selectedSpace } = this.screen;
        if (!selectedSpace) {
            throw new Error('You need to select a space first');
        }
        const media = HttpProject.fromName(name);
        const meta = Project.fromProject(media, selectedSpace);
        await this.addFile(meta.toJSON(), media.toJSON());
    }
    async addFolder(name) {
        const { selectedSpace } = this.screen;
        if (!selectedSpace) {
            throw new Error('You need to select a space first');
        }
        const space = Folder.fromName(name, selectedSpace);
        await this.addFile(space.toJSON());
    }
    async addSchema(name) {
        const { selectedSpace } = this.screen;
        if (!selectedSpace) {
            throw new Error('You need to select a space first');
        }
        const media = DataNamespace.fromName(name);
        const file = DataFile.fromDataNamespace(media, selectedSpace);
        await this.addFile(file.toJSON(), media.toJSON());
    }
    async addFile(file, media) {
        const { selectedSpace } = this.screen;
        if (!selectedSpace) {
            throw new Error('You need to select a space first');
        }
        const opts = {};
        if (this.fs.parent) {
            opts.parent = this.fs.parent;
        }
        const result = await this.screen.bindings.store.files.add(file, opts);
        if (media) {
            await this.screen.bindings.store.media.add(result.key, media, 'application/json');
        }
    }
    pageOptionsSelectHandler(e) {
        const target = e.detail.item;
        if (!target) {
            return;
        }
        const option = target.dataset.option;
        if (option === 'import-project') {
            this.screen.openDialog('importProjectDialog');
        }
        else if (option === 'refresh-list') {
            this.refresh();
        }
    }
    createSelectHandler(e) {
        const target = e.detail.item;
        if (!target) {
            return;
        }
        const option = target.dataset.option;
        if (option === 'folder') {
            this.screen.openDialog('createFolderDialog');
        }
        else if (option === 'project') {
            this.screen.openDialog('createProjectDialog');
        }
        else if (option === 'schema') {
            this.screen.openDialog('createSchemaDialog');
        }
        else if (option === 'certificate') {
            const { parent } = this.fs;
            if (parent) {
                navigate('certificates', 'add', parent);
            }
            else {
                navigate('certificates', 'add');
            }
        }
    }
    importHandler(e) {
        e.preventDefault();
        const form = e.target;
        const input = form.querySelector('ui-text-field');
        if (!input) {
            this.cancelImportDialog();
            return;
        }
        const { submitter } = e;
        if (!submitter) {
            this.cancelImportDialog();
            return;
        }
        const button = submitter; // or equivalent
        if (button.value !== 'import') {
            this.cancelImportDialog();
            return;
        }
        const { files } = input;
        if (!files || !files[0]) {
            this.cancelImportDialog();
            return;
        }
        this.processImportFile(files[0]);
    }
    async processImportFile(file) {
        this.importState = ImportState.Analyzing;
        this.screen.render();
        const processor = new DataImportProcessor();
        const analysis = await processor.fromFile(file);
        this.importState = ImportState.Analyzed;
        this.screen.render();
        this.importProcessor = processor;
        if (!analysis.error) {
            this.continueDataImport();
        }
    }
    async continueDataImport() {
        const { selectedSpace } = this.screen;
        if (!selectedSpace) {
            throw new Error('You need to select a Folder first');
        }
        const { importProcessor } = this;
        if (!importProcessor) {
            throw new Error('Invalid state. Import processor not activated.');
        }
        this.importState = ImportState.Importing;
        this.screen.render();
        try {
            await importProcessor.importProject(this.screen.bindings.store, selectedSpace, this.fs.parent);
            this.importState = ImportState.Done;
            this.screen.render();
        }
        catch (e) {
            // eslint-disable-next-line no-console
            console.error(e);
            this.importState = ImportState.Error;
        }
    }
    importDialogCloseHandler() {
        if (this.importProcessor) {
            this.importProcessor.abort();
            this.importProcessor = undefined;
        }
        this.importState = undefined;
    }
    itemActivateHandler(item) {
        const { kind } = item;
        if (kind === ProjectKind) {
            this.openProject(item.key);
        }
        else if (kind === FolderKind) {
            this.openFolder(item);
        }
        else if (kind === DataFileKind) {
            this.openDataSchema(item.key);
        }
        else {
            throw new Error(`Unknown activation item: ${kind}`);
        }
    }
    handleTableRender() {
        this.screen.render();
    }
    handleTableSelect(item) {
        if (Array.isArray(item)) {
            return;
        }
        this.selectedItem = item;
        this.screen.render();
    }
    handleTableScrollEnd() {
        this.fs.debounceQuery();
    }
    openProject(key) {
        const file = this.fs.files.find(i => i.key === key);
        if (!file) {
            throw new Error(`Invalid state: file not found`);
        }
        NavigationEvents.App.runHttpProject({
            space: file.space,
            key,
        });
    }
    openDataSchema(key) {
        const { selectedSpace } = this.screen;
        if (!selectedSpace) {
            throw new Error('The Folder is not set.');
        }
        NavigationEvents.App.runSchemaDesigner({
            key,
            space: selectedSpace,
        });
    }
    async openFolder(folder) {
        navigate('files', folder.key);
        this.selectedItem = undefined;
    }
    handleFileOptionSelect(e) {
        const item = e.detail.item;
        const list = e.target;
        const operation = item.dataset.option;
        const key = list.dataset.key;
        if (!key || !operation) {
            return;
        }
        if (operation === 'delete') {
            this.deleteFile(key);
        }
        else if (operation === 'save-file') {
            this.saveFile(key);
        }
        else if (operation === 'rename') {
            this.renameFile(key);
        }
        else if (operation === 'share') {
            this.shareFile(key);
        }
    }
    async deleteFile(key) {
        const { selectedSpace } = this.screen;
        if (!selectedSpace) {
            throw new Error(`Invalid state: Space is not selected.`);
        }
        const trashKey = await this.screen.bindings.store.files.delete(key);
        SnackNotifications.notify('The file was moved to trash.', {
            close: true,
            actionLabel: 'Undo',
            actionCallback: async () => {
                await this.screen.bindings.store.trash.restore(trashKey);
            }
        });
    }
    async saveFile(key) {
        const files = this.screen.bindings.files;
        const content = await this.screen.bindings.store.media.read(key);
        const queryResult = await files.saveFileDialog({
            excludeAcceptAllOption: true,
            title: 'Save file as...',
            filters: [
                {
                    description: 'HTTP Client files',
                    accept: {
                        'application/json': ['.json'],
                    },
                }
            ],
        });
        if (queryResult.canceled) {
            return;
        }
        const data = JSON.stringify(content);
        const path = queryResult.filePath;
        await files.writeFile(path, data, { dispose: true });
    }
    renameFile(key) {
        const file = this.fs.files.find(i => i.key === key);
        if (!file) {
            return;
        }
        const name = file.info.name || '';
        const dialog = document.createElement('rename-dialog');
        dialog.name = name;
        dialog.modal = true;
        dialog.open = true;
        document.body.appendChild(dialog);
        dialog.addEventListener('close', async (ev) => {
            document.body.removeChild(dialog);
            const event = ev;
            const { cancelled, value } = event.detail;
            if (!cancelled && value) {
                this.screen.renameFile(file, value);
            }
        });
    }
    shareFile(key) {
        const file = this.fs.files.find(i => i.key === key);
        if (!file) {
            return;
        }
        const dialog = document.createElement('share-file');
        dialog.file = file;
        dialog.user = this.screen.user;
        dialog.appInfo = AppInfo;
        dialog.modal = true;
        document.body.appendChild(dialog);
        dialog.open = true;
        dialog.addEventListener('close', () => {
            document.body.removeChild(dialog);
        });
    }
    handleSelectedShare() {
        const { selectedItem } = this;
        if (!selectedItem) {
            return;
        }
        this.shareFile(selectedItem);
    }
    handleSelectedTrash() {
        const { selectedItem } = this;
        if (!selectedItem) {
            return;
        }
        this.deleteFile(selectedItem);
    }
    render() {
        return html `
    <div class="section-header">
      <h2 class="headline-small">Your files</h2>
      ${this.renderBreadcrumbs()}
      <div class="spacer"></div>
      ${this.renderSelectedToolbar()}
      ${this.renderCreateButton()}
      ${this.renderPageMoreOptions()}
    </div>
    ${this.renderFilesTable()}
    ${this.renderCreateProjectDialog()}
    ${this.renderCreateFolderDialog()}
    ${this.renderImportDialog()}
    ${this.renderCreateSchemaDialog()}
    `;
    }
    renderSelectedToolbar() {
        const { selectedItem } = this;
        if (!selectedItem) {
            return nothing;
        }
        const file = this.fs.files.find(i => i.key === selectedItem);
        if (!file) {
            return nothing;
        }
        return html `
    ${this.renderSelectionShareButton(file)}
    ${this.renderSelectionDeleteButton(file)}
    <ui-divider vertical type="middle"></ui-divider>
    `;
    }
    renderSelectionShareButton(selected) {
        const { capabilities } = selected;
        let canShare = false;
        if (capabilities) {
            canShare = capabilities.canShare;
        }
        return html `
    <ui-icon-button
      title="Share selected file"
      aria-label="Share selected file"
      ?disabled="${!canShare}"
      @click="${this.handleSelectedShare}"
    >
      <ui-icon icon="personAdd" role="presentation"></ui-icon>
    </ui-icon-button>
    `;
    }
    renderSelectionDeleteButton(selected) {
        const { capabilities } = selected;
        let canDelete = false;
        if (capabilities) {
            canDelete = capabilities.canDelete;
        }
        return html `
    <ui-icon-button
      title="Move selected file to trash"
      aria-label="Move selected file to trash"
      ?disabled="${!canDelete}"
      @click="${this.handleSelectedTrash}"
    >
      <ui-icon icon="deleteFile" role="presentation"></ui-icon>
    </ui-icon-button>
    `;
    }
    renderCreateButton() {
        return html `
    <ui-dropdown-list
      @select="${this.createSelectHandler}" 
      horizontalAlign="right"
      closeOnOutsideClick
    >
      <ui-button type="outlined" class="new-button">
        <ui-icon icon="add" slot="icon"></ui-icon>
        New
      </ui-button>
      <ui-list slot="dropdown" role="menu">
        <ui-list-item image="icon" data-option="project" role="menuitem">
          <ui-icon icon="collectionsBookmark" slot="start"></ui-icon>
          Project
        </ui-list-item>
        <ui-list-item image="icon" data-option="schema" role="menuitem">
          <ui-icon icon="schema" slot="start"></ui-icon>
          Data schema
        </ui-list-item>
        <ui-list-item image="icon" data-option="certificate" role="menuitem">
          <ui-icon icon="certificate" slot="start"></ui-icon>
          Certificate
        </ui-list-item>
        <ui-divider></ui-divider>
        <ui-list-item image="icon" data-option="folder" role="menuitem">
          <ui-icon icon="folder" slot="start"></ui-icon>
          Folder
        </ui-list-item>
      </ui-list>
    </ui-dropdown-list>
    `;
    }
    renderPageMoreOptions() {
        return html `
    <ui-dropdown-list
      @select="${this.pageOptionsSelectHandler}" 
      horizontalAlign="right"
      closeOnOutsideClick
    >
      <ui-icon-button title="More options" aria-label="Activate for more options">
        <ui-icon icon="moreVert"></ui-icon>
      </ui-icon-button>
      <ui-list slot="dropdown" role="menu">
        <ui-list-item data-option="import-project" role="menuitem">
          Import project
        </ui-list-item>
        <ui-list-item data-option="refresh-list" role="menuitem">
          Refresh list
        </ui-list-item>
      </ui-list>
    </ui-dropdown-list>
    `;
    }
    renderBreadcrumbs() {
        const { breadcrumbs = [] } = this.fs;
        if (!breadcrumbs.length) {
            return html ``;
        }
        const items = [{
                key: '',
                kind: '',
                name: 'root',
            }].concat(breadcrumbs);
        return html `
    <nav class="breadcrumbs body-medium" aria-label="Breadcrumbs">
      <ol>
      ${join(map(items, (i) => html `<li><a href="#/files${i.key ? `/${i.key}` : ''}">${i.name}</a></li>`), html `<li aria-hidden="true"><span class="separator">/</span></li>`)}
      </ol>
    </nav>
    `;
    }
    renderFilesTable() {
        return this.dt.render();
    }
    renderEmptyTable() {
        return html `
    <p>You have no files.</p>
    <p>An HTTP project is a set of HTTP request related to an API. Use it to organize and document your HTTP requests.</p>
    `;
    }
    renderTableHeader() {
        const result = [];
        result.push(this.dt.header('Name', { class: 'name-cell' }));
        if (!this.screen.isSingleUser) {
            result.push(this.dt.header('Owner', { class: 'owner-cell' }));
        }
        result.push(this.dt.header('Updated', { class: 'updated-cell' }));
        result.push(this.dt.header(html `<span hidden aria-label="Row options">Menu</span>`, { class: 'menu-cell' }));
        return result;
    }
    renderTableItem(item) {
        const result = [];
        result.push(this.nameCell(item));
        if (!this.screen.isSingleUser) {
            result.push(this.ownerCell(item));
        }
        result.push(this.updatedCell(item));
        result.push(this.optionsCell(item));
        return result;
    }
    saveFileOption() {
        return html `
    <ui-list-item image="icon" data-option="save-file" role="menuitem" title="Saves the file on the computer">
      <ui-icon icon="save" slot="start"></ui-icon>
      Save to file
    </ui-list-item>
    `;
    }
    openFileOption() {
        return html `
    <ui-list-item image="icon" data-option="open" role="menuitem" title="Opens the file">
      <ui-icon icon="openInNew" slot="start"></ui-icon>
      Open
    </ui-list-item>
    `;
    }
    deleteFileOption(capabilities) {
        if (!capabilities || !capabilities.canDelete) {
            return nothing;
        }
        return html `
    <ui-list-item image="icon" data-option="delete" role="menuitem" title="Moves the file to Trash">
      <ui-icon icon="deleteFile" slot="start"></ui-icon>
      Delete
    </ui-list-item>
    `;
    }
    renameFileOption(capabilities) {
        if (!capabilities || !capabilities.canRename) {
            return nothing;
        }
        return html `
    <ui-list-item image="icon" data-option="rename" role="menuitem" title="Renames the file">
      <ui-icon icon="rename" slot="start"></ui-icon>
      Rename
    </ui-list-item>
    `;
    }
    shareFileOption(capabilities) {
        if (!capabilities || !capabilities.canShare) {
            return nothing;
        }
        return html `
    <ui-list-item image="icon" data-option="share" role="menuitem" title="Share the file">
      <ui-icon icon="personAdd" slot="start"></ui-icon>
      Share
    </ui-list-item>
    `;
    }
    renderFileOptions(item) {
        const { key, capabilities } = item;
        const canDelete = !!capabilities && capabilities.canDelete;
        return html `
    <ui-dropdown-list
      horizontalAlign="auto"
      verticalAlign="auto"
      closeOnOutsideClick
      @mousedown="${EventUtils.cancelEvent}" 
      @mouseup="${EventUtils.cancelEvent}" 
      @click="${EventUtils.cancelEvent}"
      @dblclick="${EventUtils.cancelEvent}"
      @select="${this.handleFileOptionSelect}"
      data-key="${key}"
    >
      <ui-icon-button title="File options" aria-label="Activate for file options">
        <ui-icon icon="moreVert"></ui-icon>
      </ui-icon-button>
      <ui-list slot="dropdown" role="menu">
        ${this.openFileOption()}
        ${this.shareFileOption(capabilities)}
        <ui-divider></ui-divider>
        ${this.saveFileOption()}
        ${this.renameFileOption(capabilities)}
        ${canDelete ? html `
        <ui-divider></ui-divider>
        ${this.deleteFileOption(capabilities)}
        ` : nothing}
      </ui-list>
    </ui-dropdown-list>
    `;
    }
    nameCell(item) {
        const icon = fileIcon(item);
        return this.dt.cell(html `
      ${icon ? html `<ui-icon icon="${icon}" class="cell-icon"></ui-icon>` : nothing}
      ${item.info.name || 'Unnamed file'}
    `, { class: 'name-cell', data: { kind: item.kind } });
    }
    ownerCell(item) {
        const { user } = this.screen;
        if (!user) {
            return this.dt.cell(html `--`, { class: 'owner-cell' });
        }
        if (item.owner === user.key) {
            return this.dt.cell(html `<span aria-label="Owned by me">me</span>`, { class: 'owner-cell' });
        }
        const content = this.ownerCellAsync(item.owner);
        const loader = html `<span class="owner-loading">loading...</span>`;
        return this.dt.cell(html `${until(content, loader)}`, { class: 'owner-cell' });
    }
    async ownerCellAsync(key) {
        const user = await UserCache.getUser(key);
        if (!user) {
            return html `
      <span aria-label="Owned by unknown user">unknown</span>
      `;
        }
        return html `<span aria-label="Owned by ${user.name}">${user.name}</span>`;
    }
    updatedCell(item) {
        const { lastModified } = item;
        return this.dt.cell(html `
      <relative-time datetime="${new Date(lastModified.time).toISOString()}"></relative-time>
    `, { class: 'updated-cell' });
    }
    optionsCell(item) {
        const content = item.kind === FolderKind ? this.renderFolderOptions(item) : this.renderFileOptions(item);
        return this.dt.cell(content, { class: 'menu-cell' });
    }
    renderFolderOptions(item) {
        const { key, capabilities } = item;
        const canDelete = !!capabilities && capabilities.canDelete;
        return html `
    <ui-dropdown-list
      horizontalAlign="auto"
      verticalAlign="auto"
      closeOnOutsideClick
      @mousedown="${EventUtils.cancelEvent}" 
      @mouseup="${EventUtils.cancelEvent}" 
      @click="${EventUtils.cancelEvent}"
      @dblclick="${EventUtils.cancelEvent}"
      @select="${this.handleFileOptionSelect}"
      data-key="${key}"
    >
      <ui-icon-button title="Folder options" aria-label="Activate for more options">
        <ui-icon icon="moreVert"></ui-icon>
      </ui-icon-button>
      <ui-list slot="dropdown" role="menu">
        ${this.shareFileOption(capabilities)}
        <ui-divider></ui-divider>
        ${this.renameFileOption(capabilities)}
        ${canDelete ? html `
        <ui-divider></ui-divider>
        ${this.deleteFileOption(capabilities)}
        ` : nothing}
      </ui-list>
    </ui-dropdown-list>
    `;
    }
    renderCreateProjectDialog() {
        return html `
    <dialog id="createProjectDialog">
      <form method="dialog" @submit="${this.createProjectHandler}">
        <h3>New Project</h3>
        <div>
          <p class="body-medium">Enter new project name</p>
          <ui-text-field 
            class="input" 
            label="Project name" 
            name="name" 
            required 
            invalidText="Project name is required" 
            @keydown="${this.screen.submitOnEnter}"
            ></ui-text-field>
        </div>
        <div class="dialog-buttons">
          <ui-button type="text" value="cancel" @click="${this.cancelCreateProjectDialog}">Cancel</ui-button>
          <ui-button type="text" value="submit" submit>Create</ui-button>
        </div>
      </form>
    </dialog>
    `;
    }
    renderCreateSchemaDialog() {
        return html `
    <dialog id="createSchemaDialog">
      <form method="dialog" @submit="${this.createSchemaHandler}">
        <h3>New Schema</h3>
        <div>
          <p class="body-medium">Enter new schema name</p>
          <ui-text-field class="input" label="Schema name" name="name" required invalidText="Schema name is required" @keydown="${this.screen.submitOnEnter}"></ui-text-field>
        </div>
        <div class="dialog-buttons">
          <ui-button type="text" value="cancel" @click="${this.cancelCreateSchemaDialog}">Cancel</ui-button>
          <ui-button type="text" value="submit" submit>Create</ui-button>
        </div>
      </form>
    </dialog>
    `;
    }
    renderCreateFolderDialog() {
        return html `
    <dialog id="createFolderDialog">
      <form method="dialog" @submit="${this.createFolderHandler}">
        <h3>New Folder</h3>
        <div>
          <p class="body-medium">Enter new folder name</p>
          <ui-text-field class="input" label="Folder name" name="name" required invalidText="Folder name is required" @keydown="${this.screen.submitOnEnter}"></ui-text-field>
        </div>
        <div class="dialog-buttons">
          <ui-button type="text" value="cancel" @click="${this.cancelCreateFolderDialog}">Cancel</ui-button>
          <ui-button type="text" value="submit" submit>Create</ui-button>
        </div>
      </form>
    </dialog>
    `;
    }
    renderImportDialog() {
        const { importState } = this;
        const submitDisabled = !!importState && [ImportState.Analyzing, ImportState.Importing].includes(importState);
        const cancelLabel = importState === ImportState.Done ? 'Close' : 'Cancel';
        const hasSubmit = importState !== ImportState.Done;
        return html `
    <dialog id="importProjectDialog" @close="${this.importDialogCloseHandler}">
      <form @submit="${this.importHandler}">
        <h3>Import Project</h3>
        <div class="dialog-contents">
          ${this.renderImportPage()}
        </div>
        <div class="dialog-buttons">
          <ui-button type="text" value="cancel" @click="${this.cancelImportDialog}">${cancelLabel}</ui-button>
          ${hasSubmit ? html `<ui-button type="text" value="import" submit ?disabled="${submitDisabled}">Import</ui-button>` : ''}
        </div>
      </form>
    </dialog>
    `;
    }
    renderImportPage() {
        const { importState } = this;
        switch (importState) {
            case ImportState.Importing: return this.renderImportWait();
            case ImportState.Done: return this.renderImportDone();
            case ImportState.Analyzed:
            case ImportState.Analyzing:
            default: return this.renderImportInput();
        }
    }
    renderImportInput() {
        const { importProcessor } = this;
        const errorMessage = importProcessor && importProcessor.analysis && importProcessor.analysis.message;
        return html `
    <p class="body-medium">Import projects from HTTP Client, Advanced REST Client, or a Postman collection.</p>
    <ui-text-field type="file" class="input" label="Project file" name="file" required invalidText="Project file is required"></ui-text-field>
    ${errorMessage ? html `<div class="import-error">${errorMessage}</div>` : ''}
    `;
    }
    renderImportWait() {
        return html `
    <p class="body-medium">Importing project...</p>
    `;
    }
    renderImportDone() {
        return html `
    <p class="body-medium">Import succeeded.</p>
    `;
    }
}
//# sourceMappingURL=Files.page.js.map