package com.atlassian.stash.internal.web.soy.functions.pagedata;

import com.atlassian.plugin.webresource.WebResourceManager;
import com.atlassian.soy.renderer.SoyServerFunction;
import com.atlassian.stash.internal.plugin.web.fragments.ClientPageDataHandler;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;

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

/**
 * Provides the requirePageData() Soy function, which requests data from PageDataProviders that will later
 * be included into the page when includePageData() is called.
 */
public class RequirePageDataFunction implements SoyServerFunction<String> {

    private final ClientPageDataHandler clientPageDataHandler;
    private final WebResourceManager webResourceManager;

    public RequirePageDataFunction(ClientPageDataHandler clientPageDataHandler, WebResourceManager webResourceManager) {
        this.clientPageDataHandler = clientPageDataHandler;
        this.webResourceManager = webResourceManager;
    }

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

    @Override
    public String apply(Object... args) {
        Preconditions.checkArgument(args[0] instanceof String, "Location must be a string");
        Preconditions.checkArgument(args[1] instanceof Map, "Context must be a map");

        String location = (String) args[0];
        Map<String, Object> contextObj = (Map<String, Object>) args[1];

        clientPageDataHandler.requirePageData(location, contextObj);
        webResourceManager.requireResource("com.atlassian.bitbucket.server.bitbucket-page-data:page-data-loader");
        return "";
    }

    @Override
    public Set<Integer> validArgSizes() {
        return ImmutableSet.of(2);
    }
}
