package ru.yandex.qe.dispenser.ws;

import java.util.Optional;
import java.util.stream.Collectors;

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.Nullable;

import ru.yandex.qe.dispenser.api.v1.DiPersonInfo;
import ru.yandex.qe.dispenser.domain.Person;
import ru.yandex.qe.dispenser.domain.Project;
import ru.yandex.qe.dispenser.domain.Service;
import ru.yandex.qe.dispenser.domain.hierarchy.Hierarchy;
import ru.yandex.qe.dispenser.domain.hierarchy.Session;
import ru.yandex.qe.dispenser.swagger.DispenserSecurityDefinition;
import ru.yandex.qe.dispenser.swagger.SwaggerTags;

@Path("/v1/persons")
@Produces(ServiceBase.APPLICATION_JSON_UTF_8)
@org.springframework.stereotype.Service("person")
@Api(tags = {SwaggerTags.DISPENSER_API}, authorizations = {@Authorization(value = DispenserSecurityDefinition.AUTHORIZATION_SCHEME_NAME)})
public class PersonService extends ServiceBase {

    private static final String LOGIN_PARAM = "login";

    @GET
    @Access
    @Path("/info")
    public DiPersonInfo getPersonInfo(@QueryParam(LOGIN_PARAM) @Nullable final Person personFromQueryParam) {
        final Person person = Optional.ofNullable(personFromQueryParam).orElse(Session.WHOAMI.get());
        return DiPersonInfo.forPerson(person.getLogin())
                .memberOfProjects(Hierarchy.get().getMemberProjects(person).stream().map(Project::getPublicKey).collect(Collectors.toSet()))
                .responsibleForProjects(Hierarchy.get().getRealResponsibleProjects(person).stream().map(Project::getPublicKey).collect(Collectors.toSet()))
                .adminOfServices(Hierarchy.get().getServiceReader().getAdminServices(person).stream().map(Service::getKey).collect(Collectors.toSet()))
                .setDispenserAdmin(Hierarchy.get().isDispenserAdmin(person))
                .build();
    }

}
