import LayoutItem from "../LayoutItem";
import LayoutItemFactory, {LayoutItemImplConfig} from "../LayoutItemFactory";

export default class SubmitButton extends LayoutItem{
    public text: string = "";

    constructor(params: Partial<SubmitButton> = {}) {
        super(params);
        Object.assign(this, params);
    }

    placeHtml(container: HTMLElement): void {
        const button = document.createElement("button");
        button.classList.toggle("pad-hidden", !this.visible);
        button.innerText = this.text;
        button.type = "button";
        button.addEventListener("click", () => {
            this.getOwnerForm().submit();
        })
        button.classList.add("pad-submit-button", "button-primary");
        button.disabled = !this.getOwnerForm().getDataNode().isValid;
        this.getOwnerForm().onSubmittingChange.add((event) => {
            button.classList.toggle("pad-submitting", event.submitting);
            button.disabled = event.submitting || button.classList.contains("pad-invalid");
        })

        this.getOwnerForm().getDataNode().onValidChange.add(event => {
            button.classList.toggle("pad-invalid", !event.isValid);
            button.disabled = !event.isValid || button.classList.contains("pad-submitting");
        });

        container.appendChild(button);
        this.placedHtml.push(button);
    }
}

export function addSubmitButtonToFactory(factory: LayoutItemFactory): void {
    factory.registerConstructor("submitButton", (config, params) => {
        const impl = config.impl;
        if (!isSubmitButtonConfig(impl)) return null;
        const submitButtonParam: Partial<SubmitButton> = params as Partial<SubmitButton>;
        submitButtonParam.text = impl.text;
        return new SubmitButton(submitButtonParam);
    })
}

function isSubmitButtonConfig(config: LayoutItemImplConfig): config is SubmitButtonConfig{
    return config.type === "submitButton";
}

interface SubmitButtonConfig extends LayoutItemImplConfig{
    type: "submitButton";
    text: string;
}