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.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.Person;

import java.util.Collections;
import java.util.Set;

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


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

    @Override
    public JsExpression generate(JsExpression... args) {
        String person = args[0].getText();
        return new JsExpression(new StringBuilder()
                .append(person)
                .append(".displayName || ")
                .append(person)
                .append(".name")
                .toString());
    }

    @Override
    public String apply(Object... args) {
        Person person = (Person) args[0];
        return person instanceof ApplicationUser ? ((ApplicationUser) person).getDisplayName() : person.getName();
    }

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