package resources;

import io.dropwizard.auth.Auth;
import objects.Solution;
import objects.User;
import repositories.SolutionsRepository;
import repositories.TasksRepository;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by gpietrus on 16.02.16.
 */
@Singleton
@Path(value = "/solutions")
@Produces(MediaType.APPLICATION_JSON)
public class SolutionsResource {

    private SolutionsRepository solutionsRepository;
    private TasksRepository tasksRepository;

    @Inject
    public SolutionsResource(SolutionsRepository solutionsRepository, TasksRepository tasksRepository) {
        this.solutionsRepository = solutionsRepository;
        this.tasksRepository = tasksRepository;
    }

    @POST
    public Response submitSolution(@Auth User user,
                                   String flag) throws Exception
    {
        if (tasksRepository.checkFlag(user.getName(), flag)) {
            return Response.ok().build();
        }
        return Response.status(Response.Status.NOT_ACCEPTABLE).build();
    }

    @GET
    @Path("/all")
    public Map<String, List<String>> getTeamsSolutions() {
        return solutionsRepository.getAll()
                .stream()
                .collect(Collectors.groupingBy(new Function<Solution, String>() {
                    @Override
                    public String apply(Solution solution) {
                        return solution.getTaskName();
                    }
                }))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .map(solution -> solution.getTeam().getName())
                                .collect(Collectors.toList())
                ));

    }

}
