import Input from "../Input";
import InputFactory, {InputImplConfig} from "../InputFactory";

export default class BoolInput extends Input<boolean>{
    constructor(params: Partial<BoolInput>) {
        super(params);
        Object.assign(this, params);
    }

    public placeHtml(container: HTMLElement): void {
        const questionContainer = this.getQuestionContainer();
        questionContainer.classList.add("pad-bool-input");
        container.append(questionContainer);
        this.placedHtml.push(questionContainer);
    }

    protected getInputElement(): HTMLElement {
        const inputElement = document.createElement("input");
        inputElement.type = "checkbox";
        inputElement.name = this.getFullPathName();
        inputElement.addEventListener("change", () => {
            this.value = inputElement.checked;
            this.getDataNode().value = inputElement.checked;
        });

        this.onChange.add(event => {
            inputElement.checked = event.value ?? false;
        });

        this.getDataNode().onChange.add(event => {
            inputElement.checked = event.value ?? false;
        })

        this.getDataNode().onReset.add( () => {
            this.value = undefined;
            inputElement.checked = this.getDataNode().valueOrDefault ?? false;
        })

        inputElement.checked = this.getDataNode().valueOrDefault ?? false;
        return inputElement;
    }

}

export function addBoolInputToFactory(factory: InputFactory): void {
    factory.registerConstructor("bool", (config, params) => {
        const impl = config.impl;
        if (!isBoolInputConfig(impl)) return null;

        const boolInputParam: Partial<BoolInput> = params as Partial<BoolInput>;

        return new BoolInput(boolInputParam);
    });
}

function isBoolInputConfig(config: InputImplConfig): config is BoolInputConfig{
    return config.type === "bool";
}

interface BoolInputConfig extends InputImplConfig{
    type: "bool";
}