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 java.util.Collections;
import java.util.Set;

import static com.google.common.base.Preconditions.checkArgument;

public class StringContainsFunction implements SoyServerFunction<Boolean>, SoyClientFunction {

    public static final Set<Integer> VALID_ARG_SIZES = Collections.singleton(2);

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

    @Override
    public JsExpression generate(JsExpression... args) {
        return new JsExpression(new StringBuilder(args[0].getText())
                .append(".indexOf(").append(args[1].getText())
                .append(") !== -1")
                .toString());
    }

    @Override
    public Boolean apply(Object... args) {
        final Object text = args[0];
        checkArgument(text instanceof String, "invalid argument: %s", text);

        return ((String) text).contains(String.valueOf(args[1]));
    }

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