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_MEDIA_WORKSPACE_CONTEXT } from '../../workspace/constants.js';
import { UmbMediaAuditLogRepository } from '../repository/index.js';
import { getMediaHistoryTagStyleAndText, TimeOptions } from './utils.js';
import { css, html, customElement, state, nothing, repeat, when } from '../../../../../external/lit/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { UmbTextStyles } from '../../../../core/style/index.js';
import { UmbPaginationManager } from '../../../../core/utils/index.js';
import { UmbUserItemRepository } from '../../../../user/user/index.js';
/**
 * @deprecated Scheduled for removal in Umbraco 19. Replaced by the shared 'auditLog' kind element (UmbContentAuditLogWorkspaceInfoAppElement).
 */
let UmbMediaHistoryWorkspaceInfoAppElement = class UmbMediaHistoryWorkspaceInfoAppElement extends UmbLitElement {
    #workspaceContext;
    #auditLogRepository;
    #pagination;
    #userItemRepository;
    #userMap;
    constructor() {
        super();
        this._currentPageNumber = 1;
        this._totalPages = 1;
        this._items = [];
        this.#auditLogRepository = new UmbMediaAuditLogRepository(this);
        this.#pagination = new UmbPaginationManager();
        this.#userItemRepository = new UmbUserItemRepository(this);
        this.#userMap = new Map();
        this.#pagination.setPageSize(10);
        this.observe(this.#pagination.currentPage, (number) => (this._currentPageNumber = number));
        this.observe(this.#pagination.totalPages, (number) => (this._totalPages = number));
        this.consumeContext(UMB_MEDIA_WORKSPACE_CONTEXT, (instance) => {
            this.#workspaceContext = instance;
            this.#requestAuditLogs();
        });
    }
    async #requestAuditLogs() {
        if (!this.#workspaceContext)
            return;
        const unique = this.#workspaceContext.getUnique();
        if (!unique)
            throw new Error('Media unique is required');
        const { data } = await this.#auditLogRepository.requestAuditLog({
            unique,
            skip: this.#pagination.getSkip(),
            take: this.#pagination.getPageSize(),
        });
        if (data) {
            this._items = data.items;
            this.#pagination.setTotalItems(data.total);
            this.#requestAndCacheUserItems();
        }
    }
    #onPageChange(event) {
        this.#pagination.setCurrentPageNumber(event.target?.current);
        this.#requestAuditLogs();
    }
    async #requestAndCacheUserItems() {
        const allUsers = this._items?.map((item) => item.user.unique).filter(Boolean);
        const uniqueUsers = [...new Set(allUsers)];
        const uncachedUsers = uniqueUsers.filter((unique) => !this.#userMap.has(unique));
        // If there are no uncached user items, we don't need to make a request
        if (uncachedUsers.length === 0)
            return;
        const { data: items } = await this.#userItemRepository.requestItems(uncachedUsers);
        if (items) {
            items.forEach((item) => {
                // cache the user item
                this.#userMap.set(item.unique, item);
                this.requestUpdate('_items');
            });
        }
    }
    render() {
        return html `
			<umb-workspace-info-app-layout headline="#general_history">
				<div id="content">
					${when(this._items, () => this.#renderHistory(), () => html `<div id="loader"><uui-loader></uui-loader></div>`)}
					${this.#renderPagination()}
				</div>
			</umb-workspace-info-app-layout>
		`;
    }
    #renderHistory() {
        if (this._items && this._items.length) {
            return html `
				<umb-history-list>
					${repeat(this._items, (item) => item.timestamp, (item) => {
                const { text, style } = getMediaHistoryTagStyleAndText(item.logType);
                const user = this.#userMap.get(item.user.unique);
                return html `<umb-history-item
								.name=${user?.name ?? 'Unknown'}
								.detail=${this.localize.date(item.timestamp, TimeOptions)}>
								<umb-user-avatar
									slot="avatar"
									.name=${user?.name}
									.kind=${user?.kind}
									.imgUrls=${user?.avatarUrls ?? []}></umb-user-avatar>

								<span class="log-type">
									<uui-tag look=${style.look} color=${style.color}>
										${this.localize.term(text.label, item.parameters)}
									</uui-tag>
									${this.localize.term(text.desc, item.parameters)}
								</span>
							</umb-history-item>`;
            })}
				</umb-history-list>
			`;
        }
        else {
            return html `${this.localize.term('content_noItemsToShow')}`;
        }
    }
    #renderPagination() {
        return html `
			${this._totalPages > 1
            ? html `
						<uui-pagination
							class="pagination"
							.current=${this._currentPageNumber}
							.total=${this._totalPages}
							firstlabel=${this.localize.term('general_first')}
							previouslabel=${this.localize.term('general_previous')}
							nextlabel=${this.localize.term('general_next')}
							lastlabel=${this.localize.term('general_last')}
							@change=${this.#onPageChange}></uui-pagination>
					`
            : nothing}
		`;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			#content {
				display: block;
				padding: var(--uui-size-space-4) var(--uui-size-space-5);
			}

			#loader {
				display: flex;
				justify-content: center;
			}

			.log-type {
				display: grid;
				grid-template-columns: var(--uui-size-40) auto;
				gap: var(--uui-size-layout-1);
			}

			.log-type uui-tag {
				justify-self: center;
				height: fit-content;
				margin-top: auto;
				margin-bottom: auto;
			}

			uui-pagination {
				flex: 1;
				display: flex;
				justify-content: center;
				margin-top: var(--uui-size-layout-1);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbMediaHistoryWorkspaceInfoAppElement.prototype, "_currentPageNumber", void 0);
__decorate([
    state()
], UmbMediaHistoryWorkspaceInfoAppElement.prototype, "_totalPages", void 0);
__decorate([
    state()
], UmbMediaHistoryWorkspaceInfoAppElement.prototype, "_items", void 0);
UmbMediaHistoryWorkspaceInfoAppElement = __decorate([
    customElement('umb-media-history-workspace-info-app')
], UmbMediaHistoryWorkspaceInfoAppElement);
export { UmbMediaHistoryWorkspaceInfoAppElement };
export default UmbMediaHistoryWorkspaceInfoAppElement;
