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

export default class Header extends LayoutItem{
    public text: string = '';
    public level: number = 3;

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

    placeHtml(container: HTMLElement): void {
        const header = document.createElement("h" + this.level);
        header.classList.toggle("pad-hidden", !this.visible);
        header.classList.add("pad-header");
        header.innerText = this.text;
        container.appendChild(header);
        this.placedHtml.push(header);
    }
}

export function addHeaderToFactory(factory: LayoutItemFactory): void {
    factory.registerConstructor("header", (config, params) => {
        const impl = config.impl;
        if (!isHeaderConfig(impl)) return null;

        const headerParam: Partial<Header> = params as Partial<Header>;
        headerParam.text = impl.text;
        headerParam.level = impl.level;

        return new Header(headerParam);
    });
}

function isHeaderConfig(config:LayoutItemImplConfig): config is HeaderConfig{
    return config.type === "header";
}

interface HeaderConfig extends LayoutItemImplConfig{
    text: string;
    level: number;
}