package com.telephoners.krakyournet.ctf.repositories;

import com.telephoners.krakyournet.ctf.beans.Team;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.exceptions.TeamNotFoundException;
import org.mongodb.morphia.Datastore;

import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class TeamsRepository extends Repository<Team>
{

    private final Datastore datastore;
    private final UsersRepository usersRepository;

    @Inject
    public TeamsRepository(Datastore datastore,
                           UsersRepository usersRepository)
    {
        super(datastore);
        this.datastore = datastore;
        this.usersRepository = usersRepository;
    }

    public Team getTeamByUser(User user)
    {
        return datastore.createQuery(Team.class).asList().stream()
                .filter(team -> team.getMembers().contains(user))
                .findFirst()
                .orElseThrow(TeamNotFoundException::new);
    }

    public Team getTeamByUserName(String username)
    {
        return getTeamByUser(usersRepository.getUserByName(username));
    }
}
