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

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

import javax.annotation.ParametersAreNonnullByDefault;

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

import ru.yandex.qe.dispenser.domain.Resource;
import ru.yandex.qe.dispenser.domain.ResourceGroup;
import ru.yandex.qe.dispenser.domain.Service;
import ru.yandex.qe.dispenser.domain.dao.InMemoryLongKeyDaoImpl;
import ru.yandex.qe.dispenser.domain.dao.resource.ResourceDao;

@ParametersAreNonnullByDefault
public class ResourceGroupDaoImpl extends InMemoryLongKeyDaoImpl<ResourceGroup> implements ResourceGroupDao {
    @Autowired
    private ResourceDao resourceDao;

    @Override
    public Set<ResourceGroup> read(final Service service) {
        return filter(group -> group.getKey().getService().equals(service))
                .collect(Collectors.toSet());
    }

    @Override
    public boolean delete(final @NotNull ResourceGroup group) {
        resourceDao.getAll()
                .stream()
                .filter(r -> group.equals(r.getGroup()))
                .forEach(r -> resourceDao.update(Resource.copyOf(r).noGroup().build()));
        return super.delete(group);
    }
}
