package ru.yandex.qe.dispenser.ws;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import io.swagger.annotations.Api;
import io.swagger.annotations.Authorization;
import org.jetbrains.annotations.NotNull;

import ru.yandex.qe.dispenser.api.v1.DiResource;
import ru.yandex.qe.dispenser.api.v1.response.DiListResponse;
import ru.yandex.qe.dispenser.domain.Resource;
import ru.yandex.qe.dispenser.domain.hierarchy.Hierarchy;
import ru.yandex.qe.dispenser.swagger.DispenserSecurityDefinition;
import ru.yandex.qe.dispenser.swagger.SwaggerTags;

@Path("/v1/resources")
@Produces(ServiceBase.APPLICATION_JSON_UTF_8)
@org.springframework.stereotype.Service("resources")
@Api(tags = {SwaggerTags.DISPENSER_API}, authorizations = {@Authorization(value = DispenserSecurityDefinition.AUTHORIZATION_SCHEME_NAME)})
public class ResourceService extends ServiceBase {
    public static final String SERVICE_PARAM = "service";

    /**
     * API для получения ресурсов одного или нескольких провайдеров
     *
     * @param serviceKeys
     * @return
     */
    @GET
    public DiListResponse<DiResource> getResources(@QueryParam(SERVICE_PARAM) @NotNull final Set<String> serviceKeys) {
        ServiceEndpointUtils.memoizeServiceValidateKeys(serviceKeys);
        final Set<Resource> allResources = Hierarchy.get()
                .getResourceReader()
                .getAll();
        Stream<Resource> filteredStream = allResources.stream();
        if (!serviceKeys.isEmpty()) {
            filteredStream = filteredStream
                    .filter(resource -> serviceKeys.contains(resource.getService().getKey()));
        }
        return new DiListResponse<>(filteredStream
                .map(Resource::toView)
                .collect(Collectors.toList()));
    }
}
