package xyz.thastertyn.Login;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import javax.security.auth.login.CredentialException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.nodes.Document;

import xyz.thastertyn.Scrape.Downloader;
import xyz.thastertyn.Types.Credentials;

public class Login {

	private String Jsessionid = null;

	/**
	 * Tries logging into SPSE Jecna. If it succeeds it also saves the JSessionId into {@link Downloader} for ease of use. If it fails to login, the program is as good as not running at all
	 * @param credentials {@link Credentials} for username anas password
	 * @throws UnknownHostException Most likely no internet connection, spsejecna.cz could not be recognised as a host
	 * @throws IOException by Jsoup
	 * @throws CredentialException The username or password is incorrect
	 * @throws TimeoutException Connection timed out, most likely a very slow internet
	 */
	public void loginJecna(Credentials credentials) throws UnknownHostException, IOException, CredentialException, TimeoutException
	{
		//#region JSESSIONID
		Connection.Response response = Jsoup.connect("https://www.spsejecna.cz")
		.header("Connection", "keep-alive")
		.method(Method.HEAD)
		.execute();

		Jsessionid = response.cookie("JSESSIONID");
		Downloader.setJSessionId(Jsessionid);
		//#endregion

		//#region Token3
		String token3 = Downloader.getConnection("https://www.spsejecna.cz/user/role?role=student")
		.get()
		.select("input[name=token3]")
		.attr("value");
		//#endregion

		//#region Login
		Downloader.getConnection("https://www.spsejecna.cz/user/login")
		.method(Connection.Method.POST)
		.header("Content-Type", "application/x-www-form-urlencoded")
		.header("Origin", "https://www.spsejecna.cz")
		.data("token3", token3)
		.data("user", credentials.getUsername())
		.data("pass", credentials.getPassword())
		.data("submit", "P%C5%99ihl%C3%A1sit+se")
		.followRedirects(true)
		.execute();
		//#endregion

		Document test = Downloader.getConnection("https://www.spsejecna.cz/score/student")
		.get();

		if(test.toString().contains("Pro pokračování se přihlaste do systému"))
		{
			throw new CredentialException("Incorrect username or password");
		}
	}

	public void loginJidelna(String user, String pass) throws UnknownHostException, IOException
	{
		//#region JSESSIONID
		Connection.Response jidelna = Jsoup.connect("https://objednavky.jidelnasokolska.cz/")
		.header("Connection", "keep-alive")
		.method(Method.HEAD)
		.execute();

		String jidelnaJSESSIONID = jidelna.cookie("JSESSIONID");
		String XSRF_TOKEN = jidelna.cookie("XSRF-TOKEN");
		//#endregion

		//#region CSRF
		String csrf = Jsoup.connect("https://objednavky.jidelnasokolska.cz/faces/login.jsp")
		.header("Connection", "keep-alive")
		.cookie("XSRF-TOKEN", XSRF_TOKEN)
		.cookie("JSESSIONID", jidelnaJSESSIONID)
		.get()
		.select("input[name=_csrf]")
		.attr("value");


		if(!XSRF_TOKEN.equals(csrf))
		{
			throw new SecurityException("CSRF tokens do not match, something is up");
		}
		//#endregion

		//#region Login
		Jsoup.connect("https://objednavky.jidelnasokolska.cz/j_spring_security_check")
		.header("Connection", "keep-alive")
		.header("Content-Type", "application/x-www-form-urlencoded")
		.cookie("XSRF-TOKEN", XSRF_TOKEN)
		.cookie("JSESSIONID", jidelnaJSESSIONID)
		.data("j_username", user)
		.data("j_password", pass)
		.data("terminal", "false")
		.data("type", "web")
		.data("_csrf", XSRF_TOKEN)
		.data("targetUrl", "/faces/secured/main.jsp?terminal=false&status=true&printer=false&keyboard=false")
		.method(Method.POST)
		.execute();
		//#endregion
	}
}
