import InteractionFactory from "./InteractionFactory";
import IStepParser from "./IStepParser";
import Step from "./Step";

export default class StepFactory {

    public stepParser: IStepParser;

    constructor(stepParser: IStepParser) {
        this.stepParser = stepParser;
    }

    public checkExpressionValidity(expression: string): Promise<boolean> {
        return this.stepParser.parseStepExpression(expression).then((ast) => {
            if (ast!== undefined && ast !== null) {
                return true;
            } else {
                throw new Error("The expression was not parser correctly");
            }
        }).catch((e) => {
            console.log(e);
            return false;
        })
    }

    public createStep(name: string, expression: string, forbiddenInteractionTextList: string[]): Promise<Step> {
        let forbiddenInteractionList = [];
        if (forbiddenInteractionTextList) {
            forbiddenInteractionList = forbiddenInteractionTextList.map(text => InteractionFactory.parseInteraction(text));
        }
        if (expression.length === 0) {
            return Promise.resolve(new Step(name, "", null, forbiddenInteractionList));
        }

        return this.stepParser.parseStepExpression(expression).then((ast) => {
            return ast.buildNFA();
        }).then((nfa) => {
            return nfa.toDFA();
        }).then((dfa) => {
            return new Step(name, expression, dfa, forbiddenInteractionList);
        });
    }

}
