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

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

public class LowerCaseFunction implements SoyServerFunction<String>, SoyClientFunction {
    public static final Set<Integer> VALID_ARG_SIZES = Collections.singleton(1);

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

    @Override
    public JsExpression generate(JsExpression... args) {
        return new JsExpression(
            new StringBuilder(args[0].getText())
                .append(".toLowerCase()")
                .toString());
    }

    @Override
    public String apply(Object... args) {
        final Object value = args[0];
        if (value instanceof String) {
            return ((String) value).toLowerCase(Locale.US);
        } else if (value instanceof Enum) {
            return ((Enum) value).name().toLowerCase(Locale.US);
        } else {
            throw new IllegalArgumentException("invalid arguments: " + value);
        }
    }

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