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;

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

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

    @Override
    public JsExpression generate(JsExpression... args) {
        return new JsExpression("require('bitbucket/internal/util/text').capInt(" + args[0].getText() + ", " + args[1].getText() + ")");
    }

    @Override
    public String apply(Object... args) {
        int input = parseInt(args[0]);
        int cap = parseInt(args[1]);

        return capInt(input, cap);
    }

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

    private static String capInt(int input, int cap) {
        // This will output the input while its less than cap, or "{cap}+" if its over.
        // This needs to be kept in sync with the JS implementation in util/text.js
        return input <= cap ? Integer.toString(input) : (cap + "+");
    }

    private static int parseInt(Object value) {
        if (value instanceof Integer) {
            return (Integer) value;
        }

        return Integer.parseInt(String.valueOf(value));
    }
}
