package com.telephoners.krakyournet.ctf.repositories;

import com.telephoners.krakyournet.ctf.objects.Solution;
import com.telephoners.krakyournet.ctf.objects.Team;
import org.mongodb.morphia.Datastore;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Singleton
public class SolutionsRepository implements Repository
{
    private Datastore datastore;

    @Inject
    public SolutionsRepository(Datastore datastore)
    {
        this.datastore = datastore;
    }

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

    public void add(Solution solution)
    { //todo
        datastore.save(solution); //todo: error handling?
        //todo: do not add if already exists
    }

    public List<Solution> getByTeam(Team team)
    {
        //todo: merge with upper
        //todo: use morphia filter
//        List<Solution> solutions = datastore.createQuery(Solution.class).asList();
        List<Solution> solutions = datastore.createQuery(Solution.class)
//                .filter("team", team)
                .asList();
        List<Solution> collect = solutions.stream()
                .filter(new Predicate<Solution>()
                {
                    @Override
                    public boolean test(Solution solution)
                    {
                        return solution.getTeam().equals(team);
                    }
                })
                .collect(Collectors.toList());
        return collect;
//        return datastore.createQuery(Solution.class).filter("team", team).asList();
        //todo: group by task
    }
}