var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { UMB_APP_LOG_VIEWER_CONTEXT } from '../../../logviewer-workspace.context-token.js';
import { UMB_LOG_VIEWER_SAVE_SEARCH_MODAL } from './log-viewer-search-input-modal.modal-token.js';
import { css, html, customElement, query, state, when, nothing } from '../../../../../../external/lit/index.js';
import { escapeHTML } from '../../../../../core/utils/index.js';
import { query as getQuery, path, toQueryString } from '../../../../../core/router/index.js';
import { umbConfirmModal, umbOpenModal } from '../../../../../core/modal/index.js';
import { UmbLitElement } from '../../../../../core/lit-element/index.js';
import { consumeContext } from '../../../../../../libs/context-api/index.js';
import { UmbStringState } from '../../../../../../libs/observable-api/index.js';
import { debounceTime, skip } from '../../../../../../external/rxjs/index.js';
import './log-viewer-search-input-modal.element.js';
let UmbLogViewerSearchInputElement = class UmbLogViewerSearchInputElement extends UmbLitElement {
    // Local state for debouncing user input before updating context
    #localQueryState;
    #logViewerContext;
    set _logViewerContext(value) {
        this.#logViewerContext = value;
        this.#observeStuff();
        this.#logViewerContext?.getSavedSearches();
    }
    get _logViewerContext() {
        return this.#logViewerContext;
    }
    constructor() {
        super();
        this._savedSearches = [];
        this._inputQuery = '';
        this._isQuerySaved = false;
        // Local state for debouncing user input before updating context
        this.#localQueryState = new UmbStringState('');
        // Debounce local input and update context
        this.observe(this.#localQueryState.asObservable().pipe(skip(1), // Skip initial value
        debounceTime(250)), (query) => {
            this._logViewerContext?.setFilterExpression(query);
            this.#persist(query);
        });
    }
    #observeStuff() {
        this.observe(this._logViewerContext?.savedSearches, (savedSearches) => {
            this._savedSearches = savedSearches?.items ?? [];
            this._isQuerySaved = this._savedSearches.some((search) => search.query === this._inputQuery);
        });
        this.observe(this._logViewerContext?.filterExpression, (query) => {
            this._inputQuery = query ?? '';
            this._isQuerySaved = this._savedSearches.some((search) => search.query === this._inputQuery);
        });
    }
    #setQuery(event) {
        const target = event.target;
        const query = target.value;
        // Update local state which will debounce before updating context
        this.#localQueryState.setValue(query);
    }
    #setQueryFromSavedSearch(query) {
        this._logViewerContext?.setFilterExpression(query);
        this.#persist(query);
        this._searchDropdownElement.open = false;
    }
    #persist(filter) {
        let query = getQuery();
        query = {
            ...query,
            lq: filter,
        };
        window.history.pushState({}, '', `${path()}?${toQueryString(query)}`);
    }
    #clearQuery() {
        this._logViewerContext?.setFilterExpression('');
        this.#persist('');
        this.#localQueryState.setValue('');
    }
    #refreshSearch() {
        // Force immediate search, bypassing debounce
        this._logViewerContext?.getLogs();
    }
    #saveSearch(savedSearch) {
        this._logViewerContext?.saveSearch(savedSearch);
    }
    async #removeSearch(name) {
        await umbConfirmModal(this, {
            headline: this.localize.term('logViewer_deleteSavedSearch'),
            content: this.localize.term('defaultdialogs_confirmdelete', escapeHTML(name)),
            color: 'danger',
            confirmLabel: this.localize.term('actions_delete'),
        });
        this._logViewerContext?.removeSearch({ name });
        //this.dispatchEvent(new UmbDeleteEvent());
    }
    async #openSaveSearchDialog() {
        umbOpenModal(this, UMB_LOG_VIEWER_SAVE_SEARCH_MODAL, {
            data: { query: this._inputQuery },
        })
            .then((savedSearch) => {
            if (savedSearch) {
                this.#saveSearch(savedSearch);
                this._isQuerySaved = true;
            }
        })
            .catch(() => { });
    }
    render() {
        return html `
			<uui-input
				id="search-input"
				label=${this.localize.term('logViewer_searchLogs')}
				.placeholder=${this.localize.term('logViewer_searchLogsPlaceholder')}
				slot="trigger"
				@input=${this.#setQuery}
				.value=${this._inputQuery}>
				${when(this._inputQuery !== '', () => html `${when(this._isQuerySaved, () => nothing, () => html `<uui-button
										compact
										slot="append"
										label=${this.localize.term('logViewer_saveSearch')}
										@click=${this.#openSaveSearchDialog}>
										<uui-icon name="icon-favorite"></uui-icon>
									</uui-button>`)}
							<uui-button
								compact
								slot="append"
								label=${this.localize.term('logViewer_refreshSearch')}
								@click=${this.#refreshSearch}>
								<uui-icon name="icon-refresh"></uui-icon>
							</uui-button>
							<uui-button compact slot="append" label=${this.localize.term('general_clear')} @click=${this.#clearQuery}>
								<uui-icon name="icon-delete"></uui-icon>
							</uui-button>`, () => nothing)}
				<umb-dropdown id="search-dropdown" slot="append" label=${this.localize.term('logViewer_savedSearches')}>
					<span slot="label"><umb-localize key="logViewer_savedSearches">Saved searches</umb-localize></span>
					<uui-scroll-container id="saved-searches-container" role="list">
						${this._savedSearches.map((search) => html `<li class="saved-search-item">
									<button
										label=${this.localize.term('logViewer_searchFor', search.name ?? '')}
										class="saved-search-item-button"
										@click=${() => this.#setQueryFromSavedSearch(search.query ?? '')}>
										<span class="saved-search-item-name">${search.name}</span>
										<span class="saved-search-item-query">${search.query}</span></button
									><uui-button
										label=${this.localize.term('logViewer_deleteThisSearch')}
										color="danger"
										@click=${() => this.#removeSearch(search.name ?? '')}
										><uui-icon name="icon-trash"></uui-icon
									></uui-button>
								</li>`)}
					</uui-scroll-container>
				</umb-dropdown>
			</uui-input>
		`;
    }
    static { this.styles = [
        css `
			:host {
				display: flex;
				align-items: center;
				justify-content: space-between;
				gap: var(--uui-size-space-4);
			}

			#search-input {
				width: 100%;
			}

			#saved-searches-button {
				flex-shrink: 0;
			}

			#saved-searches-popover {
				flex: 1;
			}

			.saved-search-item {
				display: flex;
				justify-content: space-between;
				align-items: stretch;
				border-bottom: 1px solid #e9e9eb;
			}

			.saved-search-item-button {
				display: flex;
				font-family: inherit;
				flex: 1;
				background: 0 0;
				padding: 0 0;
				border: 0;
				clear: both;
				cursor: pointer;
				display: flex;
				font-weight: 400;
				line-height: 20px;
				text-align: left;
				align-items: center;
				white-space: nowrap;
				color: var(--uui-color-interactive);
			}

			.saved-search-item-button:hover {
				background-color: var(--uui-color-surface-emphasis, rgb(250, 250, 250));
				color: var(--color-standalone);
			}

			.saved-search-item-name {
				font-weight: 600;
				margin: 0 var(--uui-size-space-3);
			}

			#polling-symbol-expand,
			#saved-search-expand-symbol,
			uui-symbol-sort {
				margin-left: var(--uui-size-space-3);
			}
		`,
    ]; }
};
__decorate([
    query('#search-dropdown')
], UmbLogViewerSearchInputElement.prototype, "_searchDropdownElement", void 0);
__decorate([
    state()
], UmbLogViewerSearchInputElement.prototype, "_savedSearches", void 0);
__decorate([
    state()
], UmbLogViewerSearchInputElement.prototype, "_inputQuery", void 0);
__decorate([
    state()
], UmbLogViewerSearchInputElement.prototype, "_isQuerySaved", void 0);
__decorate([
    consumeContext({ context: UMB_APP_LOG_VIEWER_CONTEXT })
], UmbLogViewerSearchInputElement.prototype, "_logViewerContext", null);
UmbLogViewerSearchInputElement = __decorate([
    customElement('umb-log-viewer-search-input')
], UmbLogViewerSearchInputElement);
export { UmbLogViewerSearchInputElement };
