package resources;

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

import javax.inject.Inject;
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.Optional;

/**
 * Created by gpietrus on 16.02.16.
 */
@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> getTasks() {
        return tasksRepository.getAll();
    }

    @GET
    @Path("my")
    public Collection<String> getUserFlags(@Auth User user) {
        return tasksRepository.getUserFlagsHashes(user.getName()).keySet();
    }

    //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<String> userTaskFlag = tasksRepository.getUserTaskFlag(taskUserPair.getUsername(), taskUserPair.getTaskId());//todo
        if(userTaskFlag.isPresent()) {
            return Response.ok().entity(userTaskFlag.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();
    }

}
