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 { Injectable } from '@melodicdev/core';
import { DialogRef } from './dialog-ref.class';
let DialogService = class DialogService {
    constructor() {
        this._dialogs = new Map();
    }
    addDialog(dialogID, dialogEl) {
        const dialogRef = new DialogRef(dialogID, dialogEl);
        this._dialogs.set(dialogID, {
            dialogRef,
            dialogComponent: undefined
        });
        dialogEl.addEventListener('close', () => {
            const elements = this._dialogs.get(dialogID);
            this.cleanUpDialog(dialogID, elements?.dialogComponent);
        });
        return dialogRef;
    }
    removeDialog(dialogID) {
        this._dialogs.delete(dialogID);
    }
    open(dialogComponentOrID, config) {
        let dialogID = dialogComponentOrID;
        let dialogElements = this._dialogs.get(dialogID);
        if (typeof dialogComponentOrID !== 'string') {
            const dialogComponent = this.mountDialog(dialogComponentOrID);
            const mlDialogEl = dialogComponent.shadowRoot?.querySelector('ml-dialog');
            const dialogEl = mlDialogEl.shadowRoot?.querySelector('dialog');
            dialogID = dialogEl.id;
            dialogElements = this._dialogs.get(dialogID);
            dialogElements.dialogComponent = dialogComponent;
            if (config) {
                dialogElements.dialogRef.applyConfig(config);
            }
            dialogComponent.component.onDialogRefSet?.(dialogElements.dialogRef);
        }
        dialogElements.dialogRef.open();
        return dialogElements.dialogRef;
    }
    close(dialogID, result) {
        if (this._dialogs.has(dialogID)) {
            const dialogElements = this._dialogs.get(dialogID);
            dialogElements.dialogRef.close(result);
        }
    }
    cleanUpDialog(dialogID, dialogComponent) {
        if (dialogComponent) {
            this.unmountDialog(dialogComponent);
            this.removeDialog(dialogID);
        }
    }
    mountDialog(component) {
        const dialogElement = document.createElement(component.selector);
        document.body.appendChild(dialogElement);
        return dialogElement;
    }
    unmountDialog(component) {
        component.remove();
    }
};
DialogService = __decorate([
    Injectable()
], DialogService);
export { DialogService };
