import SubmitStrategy from "./SubmitStrategy";
import Form from "../Form";
import NoAction from "./Implementations/NoAction";
import {addPostSubmitToFactory} from "./Implementations/PostSubmit";
import {addRestSubmitToFactory} from "./Implementations/RestSubmit";

export default class SubmitStrategyFactory {
    protected registeredConstructors: {[type:string]: (config:SubmitStrategyConfig, form:Form) => SubmitStrategy|null} = {};

    public createSubmitStrategy(config: SubmitStrategyConfig, form: Form): SubmitStrategy {
        if (typeof config.type !== "string" ) throw new Error("Type is not a string");
        if (!(typeof this.registeredConstructors[config.type] === "function")) return new NoAction();
        return this.registeredConstructors[config.type](config, form) ?? new NoAction();
    }

    public registerConstructor(type: string, constructor: (config:SubmitStrategyConfig, form:Form) => SubmitStrategy|null): this {
        this.registeredConstructors[type] = constructor;
        return this;
    }

    public setDefaults(): this{
        addPostSubmitToFactory(this);
        addRestSubmitToFactory(this);

        return this;
    }
}

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