package com.atlassian.bitbucket.rest.fragment;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.rest.RestResource;
import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.google.common.collect.ImmutableMap;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.List;
import java.util.Map;

public abstract class AbstractRestFragmentResource extends RestResource {

    private final RestFragmentsFactory fragmentsFactory;

    public AbstractRestFragmentResource(I18nService i18nService, RestFragmentsFactory fragmentsFactory) {
        super(i18nService);

        this.fragmentsFactory = fragmentsFactory;
    }

    protected Response executeFragments(String fragmentsLocation, Map<String, Object> body, String httpMethod,
                                        Map<String, Object> requestContext, UriInfo uriInfo) {
        if (fragmentsFactory.existsForKey(fragmentsLocation)) {
            RestFragments fragments = fragmentsFactory.forKey(fragmentsLocation, requestContext);
            RestFragmentContext fragmentContext = new DefaultRestFragmentContext(body, httpMethod, uriInfo);

            List<Object> errors = fragments.validate(fragmentContext);

            if (errors.isEmpty()) {
                return ResponseFactory
                        .ok(fragments.execute(fragmentContext))
                        .build();
            }

            return ResponseFactory
                    .status(Response.Status.BAD_REQUEST)
                    .entity(ImmutableMap.of("errors", errors))
                    .build();
        }

        return ResponseFactory.noContent().build();
    }
}