package resources;

import io.dropwizard.auth.Auth;
import objects.User;
import objects.tasks.Task;
import objects.tasks.TaskCryptoContent;
import objects.tasks.TaskWebContent;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import repositories.TasksRepository;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

/**
 * Created by gpietrus on 23.02.2016.
 */
@Path(value = "/task")
public class TaskResource {

    protected TasksRepository tasksRepository;

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

    public String readStream(InputStream input) throws IOException {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
            return buffer.lines().collect(Collectors.joining("\n"));
        }
    }

    //todo: remove proxy resource
    private InputStream proxyRequest(String url, User user) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("CTF-User", user.getName());
        CloseableHttpResponse execute = httpClient.execute(httpget);
        HttpEntity entity = execute.getEntity();
        return entity.getContent();
    }

    @Path("{task_level}")
    @GET
    public Response getTask(@Auth User user,
                            final @PathParam("task_level") int taskLevel) throws IOException {

        Task task = tasksRepository.get(taskLevel);
        if (task == null) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

        String taskText = null;

        switch (task.getTaskType()) {
            case CRYPTO:
                taskText = ((TaskCryptoContent) task.getTaskContent()).getText();
                break;
            case WEB:
                taskText = readStream(proxyRequest(((TaskWebContent) task.getTaskContent()).getUrl(), user));
                break;
        }
        return Response.ok().entity(taskText).build();
    }
}
