package xyz.thastertyn.Scrape;

import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import xyz.thastertyn.Types.Choice;
import xyz.thastertyn.Types.Option;
import xyz.thastertyn.Types.Options;

public class AbsenceList extends JecnaScrape {
	
	private ArrayList<xyz.thastertyn.Types.AbsenceList> data;
	
	private Options schoolYearOptions;

	@Override
	public void download() throws IOException
	{
		parse("https://www.spsejecna.cz/absence/student");
	}

	@Override
	public void download(Choice choice) throws IOException {

		parse(String.format(
			"https://www.spsejecna.cz/absence/student?schoolYearId=%s",
			choice.getChoices().get(0)));
	}

	private void parse(String url) throws IOException
	{
		data = new ArrayList<>();
		schoolYearOptions = new Options("Skolni R.");
		Document absenceListHTMLDocument = Downloader.download(url);

		Elements absenceLists = absenceListHTMLDocument.select("table.absence-list").select("tbody").select("tr");

		for(Element e : absenceLists)
		{
			String date = e.child(0).text();


			String text = e.child(1).text();

			data.add(
				new xyz.thastertyn.Types.AbsenceList(
					date, text));
		}

		Elements options = absenceListHTMLDocument.select("form.listConfigure").select("select[id=schoolYearId]").select("option");

		for(Element e : options)
		{
			boolean isDefault = e.hasAttr("selected");
			schoolYearOptions.addOption(new Option(e.text(), e.attr("value"), isDefault));
		}
	}

	/**
	 * Convert text to a {@link LocalDate} and try to guess the year
	 * @param text to be parsed
	 * @return {@link LocalDate} parsed
	 */
	// private LocalDate parseDate(String text)
	// {
	// 	int year = 0, month = 0, day = 0;
	// 	String[] split = text.split("\\.");

	// 	day = Integer.parseInt(split[0]);
	// 	month = Integer.parseInt(split[1]);

	// 	if(currentChoice == null)
	// 	{
	// 		// Pick the current year
	// 		int currYear = LocalDate.now().getYear();
	// 		int currMonth = LocalDate.now().getMonthValue();

	// 		if(month > currMonth && currMonth < 8)
	// 		{
	// 			year = currYear;
	// 		}else if(month < currMonth && currMonth > 8)
	// 		{
	// 			year = currYear + 1;
	// 		}else if(month < currMonth && currMonth < 8)
	// 		{
	// 			year = currYear;
	// 		}
	// 	}else{
	// 		year = Integer.parseInt(currentChoice.getChoices().get(0));
	// 	}

	// 	return LocalDate.of(year, Month.of(month), day);
	// }

	@Override
	public Options[] getOptions() {
		return new Options[] {schoolYearOptions};
	}

	public ArrayList<xyz.thastertyn.Types.AbsenceList> getData()
	{
		return data;
	}

	@Override
	public String toString()
	{
		return (!data.isEmpty()) ? data.toString() : null;
	}

}
