package com.atlassian.stash.internal.rest.repository;

import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.atlassian.bitbucket.repository.RefService;
import com.atlassian.bitbucket.repository.Repository;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Consumes({MediaType.APPLICATION_JSON})
@Produces({RestUtils.APPLICATION_JSON_UTF8})
public abstract class AbstractRepositoryRefResource {

    private final RefService refService;

    public AbstractRepositoryRefResource(RefService refService) {
        this.refService = refService;
    }

    protected Response process(Repository repository, RepositoryCallback callback) {
        Object body = callback.doWithRepository(repository, refService);
        if (body == null) {
            return ResponseFactory.status(Response.Status.NOT_FOUND).build();
        }

        Response.ResponseBuilder builder;
        if (body instanceof Response.ResponseBuilder) {
            builder = (Response.ResponseBuilder) body;
        } else {
            builder = ResponseFactory.ok(body);
        }
        return builder.build();
    }

    protected interface RepositoryCallback {

        Object doWithRepository(Repository repository, RefService refService);
    }
}
