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 ToIntFunction implements SoyServerFunction<Integer>, SoyClientFunction {
    public static final Set<Integer> VALID_ARG_SIZES = Collections.singleton(1);

    @Override
    public Integer apply(Object... args) {
        return parseInt(args[0]);
    }

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

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

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

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

    @Override
    public JsExpression generate(JsExpression... args) {
        return new JsExpression("parseInt(" + args[0].getText() + ")");
    }
}
