package repositories;

import core.ApplicationConfiguration;
import objects.Team;
import objects.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;

/**
 * Created by gpietrus on 20.02.2016.
 */
@Singleton
public class TeamsRepository implements Repository {

    private Datastore datastore;
    private ApplicationConfiguration applicationConfiguration;

    @Inject
    public TeamsRepository(Datastore datastore, ApplicationConfiguration applicationConfiguration) {
        this.datastore = datastore;
        this.applicationConfiguration = applicationConfiguration;
        initialize();
    }

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

    public void get(UUID uuid) {

    }

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

    @Override
    public void initialize() {
        this.clean();
        applicationConfiguration.getTeams().forEach(team -> {
            team.getMembers().stream().forEach(user -> datastore.save(user));
            datastore.save(team);
        });
    }

    //todo: move to interface
    public void add(Team team) {
        datastore.save(team);
    }

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

}
