package com.atlassian.bitbucket.internal.integration.jira.rest;

import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.atlassian.bitbucket.commit.Changeset;
import com.atlassian.bitbucket.integration.jira.JiraIssueService;
import com.atlassian.bitbucket.nav.NavBuilder;
import com.atlassian.bitbucket.rest.util.RestPage;
import com.atlassian.bitbucket.rest.commit.RestChangeset;
import com.atlassian.bitbucket.util.Page;
import com.atlassian.bitbucket.util.PageRequest;
import com.sun.jersey.spi.resource.Singleton;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.function.Function;

@AnonymousAllowed
@Consumes({MediaType.APPLICATION_JSON})
@Path("issues")
@Produces({RestUtils.APPLICATION_JSON_UTF8})
@Singleton
public class JiraResource {

    public static final String DEFAULT_MAX_CHANGES_PER_COMMIT = "10";

    private final JiraIssueService issueService;
    private final Function<Changeset, RestChangeset> transform;

    public JiraResource(JiraIssueService issueService, final NavBuilder navBuilder) {
        this.issueService = issueService;

        transform = changeset -> new RestChangeset(changeset, navBuilder, true);
    }

    /**
     * Retrieve a page of changesets associated with the given issue key.
     *
     * @param issueKey the issue key to search by.
     * @param maxChanges the maximum number of changes to retrieve for each changeset.
     *
     * @response.representation.200.mediaType application/json
     * @response.representation.200.qname page
     * @response.representation.200.example {@link RestChangeset#PAGE_EXAMPLE}
     * @response.representation.200.doc A page of detailed changesets.
     */
    @GET
    @Path("{issueKey}/commits")
    public Response getCommits(@PathParam("issueKey") String issueKey,
                               @Context PageRequest pageRequest,
                               @QueryParam("maxChanges") @DefaultValue(DEFAULT_MAX_CHANGES_PER_COMMIT) int maxChanges) {
        Page<Changeset> changesets = issueService.getChangesetsForIssue(issueKey, maxChanges, pageRequest);

        return ResponseFactory
                .ok(new RestPage<>(changesets, transform))
                .build();
    }
}
