package com.atlassian.bitbucket.rest.fragment;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;
import javax.ws.rs.core.UriInfo;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;

/**
 * @since 4.9
 */
public class DefaultRestFragmentContext implements RestFragmentContext {

    private final Map<String, Object> body;
    private final String httpMethod;
    private final Map<String, List<String>> queryParameters;

    public DefaultRestFragmentContext(Map<String, Object> body, String httpMethod, UriInfo uriInfo) {
        this.body = requireNonNull(body, "body");
        this.httpMethod = requireNonNull(httpMethod, "httpMethod");

        queryParameters = ImmutableMap.copyOf(requireNonNull(uriInfo, "uriInfo").getQueryParameters());
    }

    @Nonnull
    @Override
    public Optional<Object> getBodyProperty(@Nonnull String key) {
        return ofNullable(body.get(key));
    }

    @Nonnull
    @Override
    public String getMethod() {
        return httpMethod;
    }

    @Nonnull
    @Override
    public Optional<String> getQueryParameter(@Nonnull String name) {
        return getQueryParameters(name).stream().findFirst();
    }

    @Nonnull
    @Override
    public List<String> getQueryParameters(@Nonnull String name) {
        List<String> parameters = queryParameters.get(name);
        return parameters == null ? ImmutableList.of() : parameters;
    }

    @Nonnull
    @Override
    public Map<String, List<String>> getQueryParameters() {
        return queryParameters;
    }
}
