package industries.doublehelix.furrynotemanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

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

import industries.doublehelix.furrynotemanager.siteImporters.Importable;

public class WebTools {
	/**
	 * Downloads the given page and returns it as a string
	 * @param url
	 * @return the html as a string
	 * @throws IOException
	 */
	public static String getPageAsString(String url) throws IOException {
		URL theUrl = new URL(url);
		StringBuffer page = new StringBuffer();
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(theUrl.openStream()))) {
			String line;
			while((line = reader.readLine()) != null) {
			    page.append(line);
			}
		}
		return page.toString();
	}
	
	/**
	 * Downloads the given page as a JSoup document
	 * @param url
	 * @return the Document
	 * @throws IOException
	 */
	public static Document getPage(String url, String baseUrl) throws IOException {
		String s = getPageAsString(url);
		if (baseUrl == null) return Jsoup.parse(s);
		return Jsoup.parse(s, baseUrl);
	}
	
	/**
	 * Tries to get the page as a JSoup document. Tries to login if an "user has no access" page is reached
	 * @param url
	 * @param user the user to login
	 * @param importable the importable to log in to
	 * @param tries how many times it should be attempted (for wrong password or captcha at login)
	 * @return the page or null if login failed for the number of tries
	 * @throws IOException
	 */
	public static Document getPageWithLogin(String url, String baseUrl, User user, Importable importable, int tries) throws IOException {
		String page = getPageAsString(url);
		if (!importable.isAccessViolationErrorPage(page)) {
			if (baseUrl != null) return Jsoup.parse(page, baseUrl);
			return Jsoup.parse(page);
		}
		
		boolean loginWorked = false;
		while(tries >= 0) {
			loginWorked = importable.login(user);
			if (loginWorked) {
				break;
			} else {
				--tries;
			}
		}
		if (!loginWorked) return null;
		
		// 0 tries ensures that no other login will be attempted - if it doesn't work this time null is the answer
		return getPageWithLogin(url, baseUrl, user, importable, 0);
	}
}
