package ru.yandex.qe.dispenser.ws;

import java.util.Collection;
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.NotNull;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.qe.dispenser.domain.Person;
import ru.yandex.qe.dispenser.domain.YaGroup;
import ru.yandex.qe.dispenser.domain.dao.person.PersonGroupMembershipDao;
import ru.yandex.qe.dispenser.domain.hierarchy.Hierarchy;
import ru.yandex.qe.dispenser.swagger.DispenserSecurityDefinition;
import ru.yandex.qe.dispenser.swagger.SwaggerTags;
import ru.yandex.qe.dispenser.ws.abc.validator.ProjectMembersValidationResult;
import ru.yandex.qe.dispenser.ws.abc.validator.ProjectMembersValidator;

/**
 * Created by amosov-f on 13.07.16.
 * <p>
 * https://staff-api.yandex-team.ru/v3/groups?_fields=url,parent.url,members.person.login&_limit=100000
 */
@Path("/v1/staff")
@Produces(ServiceBase.APPLICATION_JSON_UTF_8)
@org.springframework.stereotype.Service("staff")
@Api(tags = {SwaggerTags.DISPENSER_API}, authorizations = {@Authorization(value = DispenserSecurityDefinition.AUTHORIZATION_SCHEME_NAME)})
public class StaffService extends ServiceBase {

    @Autowired
    private PersonGroupMembershipDao personGroupMembershipDao;
    @Autowired
    private ProjectMembersValidator projectMembersValidator;

    @GET
    @NotNull
    public Collection<String> getPersonDepartments(@QueryParam("whoami") @NotNull final String login) {
        final Person targetPerson = Hierarchy.get().getPersonReader().readPersonByLogin(login);
        return personGroupMembershipDao.getAllPersonDepartmentsByPerson(targetPerson).stream()
                .map(YaGroup::getUrl).collect(Collectors.toSet());
    }

    @GET
    @NotNull
    @Access(dispenserAdmin = true)
    @Path("/_validateRoles")
    public ProjectMembersValidationResult validateProjectsMembers() {
        return projectMembersValidator.validate();
    }

}
