// #region Imports
import { fadeOut, fadeSlideIn } from '../../../../Animations/Presets/Fade';
import { RendererServiceLocator } from '../../../../Dom/Renderer';
import { on, waitForEvent } from '@breadstone/mosaik-elements';
import { EID } from '../../../../Utilities/EId';
import { Appearance } from '../../../Types/Appearance';
import { ElevationWeight } from '../../../Types/ElevationWeight';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { DialogElement } from './DialogElement';
/**
 * Represents the `DIALOG_DEFAULT_OPTIONS` constant.
 *
 * @private
 */
const DIALOG_DEFAULT_OPTIONS = {
    height: 'auto',
    width: 'auto',
    hasBackdrop: true,
    isOpen: true,
    pressEscapeToClose: true,
    clickOutsideToClose: true,
    isDraggable: false,
    closeable: false,
    elevation: ElevationWeight.Bold,
    appearance: Appearance.Default,
    enter: fadeSlideIn,
    exit: fadeOut,
    isFullScreen: false
};
/**
 * Service for managing the display and behavior of dialog elements.
 * Provides methods to open and close dialog elements within a portal structure.
 *
 * @public
 */
export class DialogService {
    // #region Fields
    _dialogMap;
    _portalElement;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `DialogService` class.
     *
     * @public
     */
    constructor() {
        this._dialogMap = new Map();
        on(window, 'popstate', () => {
            if (this._dialogMap.size > 0) {
                for (const [key, value] of this._dialogMap) {
                    if (value.options?.navigateToClose) {
                        void this.close(key);
                    }
                }
            }
        });
    }
    async open(dialogId, wrapperClass, data, options) {
        let ref = this._dialogMap.get(dialogId);
        if (!ref) {
            // Create the wrapper component containing the dialog
            const wrapperElement = new wrapperClass(data);
            RendererServiceLocator.current.setProperty(wrapperElement, 'id', dialogId);
            // Create and attach to portal
            const portalProjection = await this.extendToPortal(wrapperElement, options);
            const dialogElement = wrapperElement.shadowRoot?.querySelector(DialogElement.is);
            if (!dialogElement) {
                throw new Error(`Dialog element not found within wrapper for ID "${dialogId}".`);
            }
            ref = {
                dialogId: dialogId,
                dialogElement: dialogElement,
                portalProjectionElement: portalProjection,
                wrapperElement: wrapperElement,
                options: options
            };
            this._dialogMap.set(dialogId, ref);
        }
        Object.assign(ref.dialogElement, {
            ...DIALOG_DEFAULT_OPTIONS,
            ...options
        });
        return new Promise((resolve) => {
            ref.resolve = resolve; // Store the resolver for use in `close`
            void ref.dialogElement.open();
            void waitForEvent(ref.dialogElement, 'closed').then(() => {
                this._dialogMap.delete(dialogId);
                void ref.portalProjectionElement.close();
                ref.portalProjectionElement.remove();
            });
        });
    }
    /**
     * Closes the dialog in the wrapper component and optionally removes the wrapper from the DOM.
     *
     * @public
     * @template TResult - Type of result returned when the dialog is closed.
     * @param {string} dialogId - Unique identifier for the dialog instance.
     * @param {TResult} [result] - Optional result returned when closing the dialog.
     * @returns {Promise<void>} A promise resolving once the dialog is fully closed.
     */
    async close(dialogId, result) {
        return new Promise((resolve) => {
            const ref = this._dialogMap.get(dialogId);
            if (ref) {
                this._dialogMap.delete(dialogId);
                void waitForEvent(ref.dialogElement, 'closed').then(() => {
                    void ref.portalProjectionElement.close();
                    ref.portalProjectionElement.remove();
                    if (ref.resolve) {
                        ref.resolve(result);
                    }
                    resolve();
                });
                void ref.dialogElement.close();
            }
            else {
                console.error(`Wrapper with ID "${dialogId}" not found.`);
                resolve(); // Resolve to avoid hanging promise if dialog not found
            }
        });
    }
    /**
     * Extends the dialog component by placing it within a portal structure.
     *
     * @private
     * @param portalProps - Properties to set on the portal.
     * @param element - The element to place within the portal.
     * @returns The created PortalElement containing the dialog.
     */
    extendToPortal(element, props) {
        return new Promise((resolve) => {
            if (!this._portalElement) {
                this._portalElement = RendererServiceLocator.current.createElement(PortalElement.is);
                RendererServiceLocator.current.setAttribute(this._portalElement, 'id', EID.next(PortalElement.is));
                Object.assign(this._portalElement, props);
                this._portalElement.addEventListener('portalAttached', (e) => {
                    console.log('portalAttached', e);
                    resolve(e.detail.projection);
                });
                RendererServiceLocator.current.appendChild(document.body, this._portalElement);
            }
            RendererServiceLocator.current.appendChild(this._portalElement, element);
        });
    }
}
/**
 * @public
 */
export class DialogServiceLocator {
    // #region Fields
    static _current = null;
    // #endregion
    // #region Properties
    static get current() {
        if (!DialogServiceLocator.isSet()) {
            throw new Error('\'DialogService\' not set.');
        }
        return DialogServiceLocator._current;
    }
    // #endregion
    // #region Methods
    static isSet() {
        return DialogServiceLocator._current !== null;
    }
    static set(current) {
        DialogServiceLocator._current = current;
    }
}
/**
 * @public
 */
DialogServiceLocator.set(new DialogService());
//# sourceMappingURL=DialogService.js.map