package ru.yandex.qe.dispenser.domain.dao.group;

import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.qe.dispenser.domain.YaGroup;
import ru.yandex.qe.dispenser.domain.dao.InMemoryLongKeyDaoImpl;
import ru.yandex.qe.dispenser.domain.dao.person.PersonGroupMembershipDao;
import ru.yandex.qe.dispenser.domain.dao.person.PersonProjectRelations;

public final class GroupDaoImpl extends InMemoryLongKeyDaoImpl<YaGroup> implements GroupDao {
    private PersonProjectRelations relations;
    private PersonGroupMembershipDao groupMembershipDao;

    @Override
    public void createIfAbsent(@NotNull final Collection<YaGroup> groups) {
        groups.forEach(this::createIfAbsent);
    }

    @Override
    public boolean delete(@NotNull final YaGroup group) {
        relations.detach(group);
        groupMembershipDao.deleteAll(groupMembershipDao.filter(m -> m.getGroup().getId() == group.getId()).collect(Collectors.toList()));
        return super.delete(group);
    }

    @Autowired
    public void setRelations(@NotNull final PersonProjectRelations relations) {
        this.relations = relations;
    }

    @Autowired
    public void setGroupMembershipDao(final PersonGroupMembershipDao groupMembershipDao) {
        this.groupMembershipDao = groupMembershipDao;
    }

    @Override
    @NotNull
    public Optional<YaGroup> tryReadYaGroupByStaffId(final long staffId) {
        // Slow search, must never use in production
        return filter(g -> Objects.equals(g.getStaffId(), staffId)).findFirst();
    }

    @Override
    @NotNull
    public Set<YaGroup> tryReadYaGroupsByStaffIds(@NotNull final Collection<Long> staffIds) {
        // Slow search, must never use in production
        return filter(g -> staffIds.contains(g.getStaffId())).collect(Collectors.toSet());
    }

    @Override
    @NotNull
    public Optional<YaGroup> tryReadYaGroupByUrl(@NotNull final String url) {
        // Slow search, must never use in production
        return filter(g -> g.getUrl().equals(url)).findFirst();
    }

    @Override
    @NotNull
    public Set<YaGroup> tryReadYaGroupsByUrls(@NotNull final Collection<String> urls) {
        // Slow search, must never use in production
        return filter(g -> urls.contains(g.getUrl())).collect(Collectors.toSet());
    }

}
