package no.valg.valgnatt.backend.rapport;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class PostToURL {
	private static final int CONNECT_TIMEOUT = 10000; // 10 sek
	private static final int READ_TIMEOUT = 60000; // 60 sek

	private String urlStr;
	private String json;
	private int result;
	private String data;
	private Exception exception;

	PostToURL(String urlStr, String requestStr) {
		this.urlStr = urlStr;
		this.json = requestStr;
	}

	int getResult() {
		return result;
	}

	public String getData() {
		return data;
	}

	public Exception getException() {
		return exception;
	}

	PostToURL utfør() {
		HttpURLConnection conn = null;
		result = 0;
		data = "";
		exception = null;
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) (url.openConnection());
			conn.setDoOutput(true);
			conn.setRequestProperty("Content-Type", "application/requestStr; charset=utf-8");
			String userInfo = url.getUserInfo();
			if (userInfo != null) {
				conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(userInfo.getBytes("UTF-8")));
			}
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setReadTimeout(READ_TIMEOUT);
			conn.connect();
			OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
			os.write(json);
			os.close();
			result = conn.getResponseCode();
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			data = br.readLine();
			br.close();
		} catch (IOException e) {
			exception = e;
		}
		if (conn != null) {
			conn.disconnect();
		}
		return this;
	}

}
