import LayoutItem from "../LayoutItem";
import {hideElement, setElementVisibility} from "../../../Utility/ElementVisibility";
import LayoutItemFactory, {LayoutItemImplConfig} from "../LayoutItemFactory";

export default class MessageDisplay extends LayoutItem{
    protected outputElements: HTMLParagraphElement[] = [];
    public classes: string[] = [];
    protected message: string|null = null;
    
    constructor(params: Partial<MessageDisplay>) {
        super(params);
        Object.assign(this, params);
    }

    public placeHtml(container: HTMLElement): void {
        const messageDiv = document.createElement("div");
        messageDiv.title = "Click to close";
        messageDiv.classList.add("pad-message", "pad-hidden", ...this.classes);
        const message = document.createElement("p");
        messageDiv.append(message);

        const closeMessageDiv = document.createElement("div");
        closeMessageDiv.classList.add("pad-close-button");
        closeMessageDiv.innerText = "X";
        messageDiv.addEventListener("click", () => {
            hideElement(messageDiv);
        })
        messageDiv.append(closeMessageDiv);

        container.append(messageDiv);
        this.placedHtml.push(messageDiv);
        this.outputElements.push(message);
    }

    public updateMessage(message: string|null): void {
        this.message = message;
        this.outputElements.forEach(html => {
            html.innerHTML = message ?? "";
            setElementVisibility(html, (message ?? "") !== "")
        });

        this.placedHtml.forEach(html => {
            setElementVisibility(html, (message ?? "") !== "")
        })
    }
}

export function addMessageDisplayToFactory(factory: LayoutItemFactory): void {
    factory.registerConstructor("messageDisplay", (config, params) => {
        const impl = config.impl;
        if (!isMessageDisplayConfig(impl)) return null;
        
        const messageDisplayParam: Partial<MessageDisplay> = params as Partial<MessageDisplay>;
        messageDisplayParam.classes = impl.classes
        
        const messageDisplay = new MessageDisplay(messageDisplayParam);
        messageDisplay.getOwnerForm().onMessageChange.add((event) => {
            messageDisplay.updateMessage(event.message);
        })

        return messageDisplay;
    });
}

function isMessageDisplayConfig(config:LayoutItemImplConfig): config is MessageDisplayConfig{
    return config.type === "messageDisplay";
}

interface MessageDisplayConfig extends LayoutItemImplConfig{
    classes: string[];
}