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.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 org.mongodb.morphia.annotations.Entity;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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

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

    public WebTask()
    {
    }

    public String getTextForUser(User user, String path) throws IOException
    {
        String url = URL_JOINER.join(getUrl(), path);
        return StreamUtils.readStream(proxyRequest(url, user));
    }

    public String getUrl()
    {
        return url;
    }

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

    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();
    }
}
