package org.bdware.sc.visitor;

import org.bdware.sc.node.ContractNode;
import org.bdware.sc.node.FunctionNode;
import org.bdware.sc.parser.YJSParser;
import org.bdware.sc.parser.YJSParserBaseVisitor;

public class FunctionDependencyVisitor extends YJSParserBaseVisitor<FunctionNode> {

    public static String APPLY = ".apply";
    public static String CALL = ".call";

    private final ContractNode cn;
    private final FunctionNode fn;

    public FunctionDependencyVisitor(ContractNode cn, FunctionNode fn) {
        this.cn = cn;
        this.fn = fn;
    }

    @Override
    public FunctionNode visitArgumentsExpression(YJSParser.ArgumentsExpressionContext ctx) {
        super.visitArgumentsExpression(ctx);
        for (FunctionNode f : cn.getFunctions()) {
            if (ctx.singleExpression().getText().equals(f.functionName) ||
                    ctx.singleExpression().getText().equals(f.functionName + APPLY) ||
                    ctx.singleExpression().getText().equals(f.functionName + CALL)) {
                fn.addDependentFunctions(f.functionName);
                break;
            }
        }
        return fn;
    }

    @Override
    public FunctionNode visitNewExpression(YJSParser.NewExpressionContext ctx) {
        super.visitNewExpression(ctx);
        for (FunctionNode f : cn.getFunctions()) {
            if (f.functionName.equals(ctx.singleExpression().getText())) {
                fn.addDependentFunctions(f.functionName);
                break;
            }
        }
        return fn;
    }

}
