import { UmbServerFileRenamedEntityEvent } from '../event/index.js';
import { UmbControllerBase } from '../../../../../libs/class-api/index.js';
import { ensurePathEndsWithSlash, umbUrlPatternToString } from '../../../utils/index.js';
import { UMB_ACTION_EVENT_CONTEXT } from '../../../action/index.js';
export const UmbServerFileRenameWorkspaceRedirectControllerAlias = Symbol('ServerFileRenameWorkspaceRedirectControllerAlias');
export class UmbServerFileRenameWorkspaceRedirectController extends UmbControllerBase {
    #actionEventContext;
    #workspaceContext;
    #router;
    constructor(host, workspaceContext, router) {
        super(host, UmbServerFileRenameWorkspaceRedirectControllerAlias);
        this.#workspaceContext = workspaceContext;
        this.#router = router;
        this.consumeContext(UMB_ACTION_EVENT_CONTEXT, (context) => {
            this.#actionEventContext = context;
            if (this.#actionEventContext) {
                this.#actionEventContext.removeEventListener(UmbServerFileRenamedEntityEvent.TYPE, this.#onFileRenamed);
                this.#actionEventContext.addEventListener(UmbServerFileRenamedEntityEvent.TYPE, this.#onFileRenamed);
            }
        });
    }
    #onFileRenamed = ((event) => {
        if (!this.#router)
            throw new Error('Router is required for this controller.');
        // Don't redirect if the event is not for the current entity
        const currentUnique = this.#workspaceContext.getUnique();
        const eventUnique = event.getUnique();
        if (currentUnique !== eventUnique)
            return;
        const newUnique = event.getNewUnique();
        if (!newUnique)
            throw new Error('New unique is required for this event.');
        const routerPath = this.#router.absoluteRouterPath;
        if (!routerPath)
            throw new Error('Router path is required for this controller.');
        const newPath = umbUrlPatternToString(ensurePathEndsWithSlash(routerPath) + 'edit/:unique', {
            unique: newUnique,
        });
        this.destroy();
        window.history.replaceState(null, '', newPath);
    });
    destroy() {
        super.destroy();
        this.#actionEventContext?.removeEventListener(UmbServerFileRenamedEntityEvent.TYPE, this.#onFileRenamed);
    }
}
