package com.telephoners.krakyournet.ctf.repositories;

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

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Singleton
public class TeamsRepository extends Repository<Team>
{

    private Datastore datastore;
    private UsersRepository usersRepository;

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

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

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

    public void get(UUID uuid)
    {

    }

    public List<Team> getAll()
    {
        return datastore.createQuery(Team.class).asList();
    }

    //todo: move to interface
    //todo: use default as interface-implemented methods
    public void add(Team team)
    {
        datastore.save(team);
    }

    //todo: move clean to upper class?
    public void clean()
    {
        datastore.getCollection(Team.class).drop();
    }
}
