import Condition from "./Condition";
import FormBuilder from "../FormBuilder";
import {addInputValueConditionToFactory} from "./InputValueCondition";

export default class ConditionFactory {
    protected registeredConstructors: {[type:string]: (config:ConditionConfig, params: Partial<Condition>) => Condition | null} = {};

    constructor(
        protected formBuilder: FormBuilder
    ) {}

    public createCondition(config: ConditionConfig): Condition|null {
        if (typeof config.type !== "string" ) throw new Error("Type is not a string");
        if (!(typeof this.registeredConstructors[config.type] === "function")) return null;

        const conditionParam: Partial<Condition> = {};
        conditionParam.formBuilder = this.formBuilder;
        return this.registeredConstructors[config.type](config, conditionParam);
    }

    public registerConstructor(type: string, constructor: (config:ConditionConfig, params: Partial<Condition>) => Condition | null): this {
        this.registeredConstructors[type] = constructor;
        return this;
    }

    public setDefaults(): this{
        addInputValueConditionToFactory(this);
        return this;
    }
}

export interface ConditionConfig {
    type: string;
    config: object;
}