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

import com.fasterxml.jackson.annotation.JsonInclude;
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;

    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) throws IOException
    {
        return StreamUtils.readStream(proxyRequest(getUrl(), 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();
    }
}
