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.stash.internal.web.fragments.WebFragmentSupport;
import com.atlassian.stash.internal.web.fragments.WebItemData;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.atlassian.stash.internal.web.soy.functions.SoyArgumentUtils.argCountFromTo;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public class WebItemFunction implements SoyServerFunction<List<WebItemData>>, SoyClientFunction {

    private static final Set<Integer> VALID_ARG_SIZES = argCountFromTo(1, 2);
    private final WebFragmentSupport webFragmentSupport;


    public WebItemFunction(WebFragmentSupport webFragmentSupport) {
        this.webFragmentSupport = webFragmentSupport;
    }

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

    @Override
    public JsExpression generate(JsExpression... args) {
        checkArgument(VALID_ARG_SIZES.contains(args.length), "invalid number of arguments: %s", args.length);
        return new JsExpression("WebFragments.getWebItems(" +
                                args[0].getText() +
                                (args.length > 1 ? "," + args[1].getText() : "") +
                                ")");
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<WebItemData> apply(Object... args) {
        checkArgument(VALID_ARG_SIZES.contains(args.length), "invalid number of arguments: %s", args.length);

        final String location = (String) checkNotNull(args[0]);
        final Map<String, Object> context = args.length == 2 && args[1] != null ?
                (Map<String, Object>) args[1] :
                Maps.<String, Object>newHashMap();

        return webFragmentSupport.getWebItems(location, context, false);
    }


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