package com.atlassian.stash.internal.web.soy.functions;

import com.atlassian.soy.renderer.JsExpression;
import com.atlassian.soy.renderer.SoyClientFunction;
import com.atlassian.soy.renderer.SoyServerFunction;
import com.google.common.base.Preconditions;

import java.util.Set;

import static com.atlassian.stash.internal.web.soy.functions.SoyArgumentUtils.argCountOf;

public class CliCommandEscapeFunction implements SoyServerFunction<String>, SoyClientFunction {
    private static final Set<Integer> VALID_ARG_SIZES = argCountOf(1);

    public CliCommandEscapeFunction() {
    }

    @Override
    public String getName() {
        return "escape_cli";
    }

    @Override
    public String apply(Object... args) {
        Preconditions.checkArgument(args.length == 1, "Wrong number of arguments (1 expected)");
        Preconditions.checkArgument(args[0] instanceof String, "The first argument, the cli command to escape, should be a string");

        String command = (String) args[0];
        return command.replace("\\", "\\\\").replace("\"", "\\\"");
    }

    @Override
    public JsExpression generate(JsExpression... jsArgs) {
        final StringBuilder sb = new StringBuilder();
        sb.append(jsArgs[0].getText())
            .append(".replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')");
        return new JsExpression(sb.toString());
    }

    @Override
    public Set<Integer> validArgSizes() {
        return VALID_ARG_SIZES;
    }
}
