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.collect.ImmutableSet;

import java.util.Set;

public class SubStringFunction implements SoyServerFunction<String>, SoyClientFunction {

    public static final Set<Integer> VALID_ARG_SIZES = ImmutableSet.of(2, 3);

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

    @Override
    public JsExpression generate(JsExpression... args) {
        final StringBuilder sb = new StringBuilder();
        sb.append(args[0].getText())
                .append(".substring(").append(args[1].getText());
        if (args.length == 3) {
            sb.append(", ").append(args[2].getText());
        }
        sb.append(")");

        return new JsExpression(sb.toString());
    }

    @Override
    public String apply(Object... args) {
        final String parent = (String) args[0];
        final int beginIndex = ((Number) args[1]).intValue();
        if (args.length == 2) {
            return parent.substring(beginIndex);
        } else {
            final int endIndex = ((Number) args[2]).intValue();
            return parent.substring(beginIndex, endIndex);
        }
    }

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