package parsers;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import com.google.common.base.Strings;

import controllers.DatabaseController;

public class AtgParser implements Parser {

	private AtgParser() {};

	private static final AtgParser instance = new AtgParser();

	private static final String defaultPath = "https://www.atg.se/spel/";

	public static AtgParser getInstance() {
		return instance;
	}

	/**
	 *
	 * @param type - V75, V65, ...
	 */
	public void getTodaysStartsFromATG(String type) {
		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		final String currentDate = dateFormat.format(new Date());
		getAtgRaces(type, currentDate);
	}

	private void getAtgRaces(String type, final String date) {
		final WebClient webclient = MyWebClient.getInstance().getWebclient();

		final String url = defaultPath + date + "/" + type;

		try {
			final HtmlPage page = webclient.getPage(url);
			webclient.waitForBackgroundJavaScript(10000);
			webclient.waitForBackgroundJavaScriptStartingBefore(10000);

			final List<HtmlSpan> spans = page.getByXPath("//span[contains(@class,'horse-name')]");

			int i = 1;
			for (final HtmlSpan hs : spans) {
				final String horseName = hs.getTextContent().trim();
				System.out.println(i++ + "/" + spans.size() + " Getting horse with name: " + horseName);
				final int horseId = TravsportParser.getInstance().getHorseIdByName(horseName);
				//				TravsportParser.getInstance().getHorseStats(type, "ts" + horseId);
				TravsportParser.getInstance().getHorseStatByIdJson(horseId, horseName, type, -1);
			}
		} catch (FailingHttpStatusCodeException | IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public void getStartsForDay(String date, String type) {
		if (!date.matches("\\d{4}-\\d{2}-\\d{2}")) {
			System.out.println(date + " is incorrect, should be yyyy-MM-dd");
			return;
		}

		getAtgRaces(type, date);
	}

	public void getResultsForDate(String type, String date) {
		final WebClient webclient = MyWebClient.getInstance().getWebclient();
		final String url = defaultPath + date + "/" + type + "/resultat";
		try {
			final HtmlPage page = webclient.getPage(url);
			webclient.waitForBackgroundJavaScript(10000);
			webclient.waitForBackgroundJavaScriptStartingBefore(10000);

			final List<HtmlTable> tables = page.getByXPath("//table[@class='game-table']");

			for (final HtmlTable htmlTable : tables) {
				final List<HtmlTableRow> rows = htmlTable.getRows();
				for (final HtmlTableRow tr : rows) {
					final String placement = tr.getCell(0).getTextContent();

					final int result = Strings.isNullOrEmpty(placement.replaceAll("\\D", ""))?-1:Integer.valueOf(placement.replaceAll("\\D", ""));

					final String horseName = ((HtmlSpan)tr.getCell(1).getByXPath("//span[contains(@class,'horse-name'")).getTextContent();
					final String driverName =  ((HtmlSpan)tr.getCell(2).getFirstChild()).getTextContent();

					final String time = tr.getCell(5).getTextContent();

					final String timeModifier = getTimeModifierFromTimeCellValue(time);
					final float timeValue = getTimeFromTimeCellValue(time);

					DatabaseController.getInstance().updateResult(horseName, driverName, result,timeModifier, timeValue, date, type);

				}
			}

		} catch (FailingHttpStatusCodeException | IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}

	}

	@Override
	public float getTimeFromTimeCellValue(String timeCell) {
		final float returnValue;
		final Pattern timePattern = Pattern.compile("\\d\\.\\d{0,2}");
		final Matcher matcher = timePattern.matcher(timeCell);
		if (matcher.find()) {
			returnValue = Float.valueOf(matcher.group());
		} else {
			returnValue = -1f;
		}

		return returnValue;
	}

}
