package com.telephoners.krakyournet.ctf.beans.tasks;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.base.Joiner;
import com.telephoners.krakyournet.ctf.beans.Flag;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.helpers.StreamUtils;
import org.apache.http.Header;
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 org.mongodb.morphia.annotations.Entity;

import javax.ws.rs.container.ContainerRequestContext;
import java.io.IOException;
import java.util.List;

@Entity("tasks")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class WebTask extends Task
{
    private String url;
    private static final String KYN_HEADER_NAME = "KYN_2016"; //todo

    public WebTask(String name, int level, String description, List<Flag> flags, String url)
    {
        super(name, level, description, flags);
        this.url = url;
    }

    public WebTask()
    {
    }

    @Override
    public TaskResponse getTaskResponse(User user, String path, ContainerRequestContext context) throws IOException
    {
        String url = getUrl() + path;
        String kynHeaderValue = context.getHeaderString(KYN_HEADER_NAME);
        CloseableHttpResponse response = proxyRequest(url, user, kynHeaderValue);
        String text = StreamUtils.readStream(response.getEntity().getContent());
        Header kynHeader = response.getFirstHeader(KYN_HEADER_NAME);
        return new TaskResponse(text, kynHeader != null ? kynHeader.getValue() : null); //todo: needs refactorig
    }

    public String getUrl()
    {
        return url;
    }

    public void setUrl(String url)
    {
        this.url = url;
    }

    private CloseableHttpResponse proxyRequest(String url, User user, String kynHeaderValue) throws IOException
    {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("CTF-User", user.getName()); //todo: is it necessary?
        httpget.setHeader("KYN_2016", kynHeaderValue); //todo: move to configuration
        return httpClient.execute(httpget);
    }
}
