package com.telephoners.krakyournet.ctf.resources;

import com.telephoners.krakyournet.ctf.beans.Team;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.repositories.SolutionsRepository;
import com.telephoners.krakyournet.ctf.repositories.TasksRepository;
import com.telephoners.krakyournet.ctf.repositories.TeamsRepository;
import io.dropwizard.auth.Auth;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Singleton
@Path(value = "/solutions")
@Produces(MediaType.APPLICATION_JSON)
public class SolutionsResource
{
    private TeamsRepository teamsRepository;
    private SolutionsRepository solutionsRepository;
    private TasksRepository tasksRepository;

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

    @POST
    @Path("/{task_level}")
    public Response submitSolution(@Auth User user,
                                   @PathParam("task_level") int taskLevel,
                                   String hash) throws Exception
    {
        if (tasksRepository.checkHash(user, hash, taskLevel)) {
            return Response.ok().build();
        }
        return Response.status(Response.Status.NOT_ACCEPTABLE).build();
    }

    @GET
    @Path("/completed")
    public List<Integer> getTeamCompletedTasks(@Auth User user)
    {
        Optional<Team> team = teamsRepository.getTeamByUser(user);
        return tasksRepository.getCompletedTasks(team.get());
    }

    @GET
    @Path("/completed/all")
    public Map<String, List<Integer>> getAllTeamsCompletetdTasks(@Auth User user)
    {
        return teamsRepository.getAll()
                .stream()
                .collect(Collectors.toMap(
                        Team::getName,
                        team -> tasksRepository.getCompletedTasks(team)
                        ));
    }

    @GET
    @Path("/my")
    public Map<Integer, List<String>> getTeamSolutions(@Auth User user)
    {
        Optional<Team> team = teamsRepository.getTeamByUser(user);
        return solutionsRepository.getTeamSolutions(team.get());
    }

    @GET
    @Path("/all")
    //todo: should return completed, not all flags?
    public Map<String, Map<Integer, List<String>>> getTeamsSolutions()
    {
        return teamsRepository.getAll()
                .stream()
                .collect(Collectors.toMap(
                        Team::getName,
                        team -> solutionsRepository.getTeamSolutions(team)
                ));
    }

}
