package com.atlassian.stash.internal.web.fragments;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.ContextProvider;
import com.atlassian.bitbucket.pull.PullRequestSearchRequest;
import com.atlassian.bitbucket.pull.PullRequestService;
import com.atlassian.bitbucket.pull.PullRequestState;
import com.atlassian.bitbucket.repository.Repository;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;

import java.util.Locale;
import java.util.Map;

public class PullRequestCountContextProvider implements ContextProvider {

    public static final String REPOSITORY = "repository";

    private final PullRequestService pullRequestService;
    private PullRequestState state;

    public PullRequestCountContextProvider(PullRequestService pullRequestService) {
        this.pullRequestService = pullRequestService;
    }

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
        String stateStr = params.get("state");
        if (stateStr == null) {
            throw new PluginParseException("<param name=\"state\">{state_name}</param> is required. Valid state_names are " +
                                           getAllowedStateValuesString());
        }

        try {
            state = PullRequestState.valueOf(stateStr);
        } catch (IllegalArgumentException iae) {
            /* Handled below */
        }

        if (state == null) {
            throw new PluginParseException("The value of param 'state' was not a valid PullRequestState. Valid values are " +
                                           getAllowedStateValuesString());
        }
    }

    private String getAllowedStateValuesString() {
        return StringUtils.join(PullRequestState.values(), ", ");
    }

    @Override
    public Map<String, Object> getContextMap(Map<String, Object> context) {
        Repository repository = (Repository) context.get(REPOSITORY);

        long count = pullRequestService.count(new PullRequestSearchRequest.Builder()
                .toRepositoryId(repository.getId())
                .state(state)
                .build());

        return ImmutableMap.<String, Object>of(
                "state", state.name().toLowerCase(Locale.US),
                "count", count);
    }
}
