package resources;

import helpers.TaskUserPair;
import io.dropwizard.auth.Auth;
import objects.User;
import objects.tasks.Task;
import repositories.TasksRepository;

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

/**
 * Created by gpietrus on 16.02.16.
 */
@Singleton
@Path(value = "/tasks")
@Produces(MediaType.APPLICATION_JSON)
public class TasksResource
{
    private TasksRepository tasksRepository;

    @Inject
    public TasksResource(TasksRepository tasksRepository) {
        this.tasksRepository = tasksRepository;
    }

    @GET
    public List<Task> getTasksPublic() {
        return tasksRepository.getAllPublic();
    }

    //todo: make it admin endpoint, any username as parameter
    //todo: admin authorization
    @GET
    @Path("my")
    public Collection<String> getUserFlags(@Auth User user) {
        Map<List<String>, Integer> userFlagsHashes = tasksRepository.getUserFlagsHashes(user.getName());
        return userFlagsHashes.entrySet()
                .stream()
                .flatMap(listIntegerEntry -> listIntegerEntry.getKey().stream())
                .collect(Collectors.toList());
    }

    //todo: merge with upper
    //todo: pass username in header via proxy?
    @POST
    //todo: authorization
    @Path("/flags/user_task_flag")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response getUserTaskFlag(@Valid final TaskUserPair taskUserPair) {

        Optional<List<String>> userTaskFlags = tasksRepository.getUserTaskFlags(taskUserPair.getUsername(), taskUserPair.getTaskLevel());//todo
        if(userTaskFlags.isPresent()) {
            return Response.ok().entity(userTaskFlags.get()).build();
        }
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

//    example json:
//    {
//        "username": "gpietrus2",
//            "taskId": "abb6b014-1ee0-4f53-b8df-c7029335c070"
//    }


    //todo: move to solutions resource
    @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();
    }

}
