package net.vexelon.currencybg.srv.remote;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.collect.Lists;

import net.vexelon.currencybg.srv.Defs;
import net.vexelon.currencybg.srv.db.models.CurrencyData;
import net.vexelon.currencybg.srv.db.models.Sources;
import net.vexelon.currencybg.srv.reports.Reporter;
import net.vexelon.currencybg.srv.utils.DateTimeUtils;

public class CryptoBGSource extends AbstractSource {

	private static final Logger log = LoggerFactory.getLogger(TavexSource.class);
	private static final String TAG_NAME = CryptoBGSource.class.getSimpleName();

	private static final String URL_SOURCE = "https://crypto.bg/tickers_header";
	private static final String DATE_FORMAT = "dd.MM.yyyy HH:mm";

	private String htmlData;

	public CryptoBGSource(Reporter reporter) {
		super(reporter);
		// TODO Auto-generated constructor stub
	}

	/**
	 * Transforms Tavex HTML data into {@link CurrencyData} models.
	 * 
	 * @param input
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 */
	public List<CurrencyData> getCryptoRates(InputStream input) throws IOException, ParseException {
		List<CurrencyData> result = Lists.newArrayList();

		Document doc = Jsoup.parse(input, Charsets.UTF_8.name(), URL_SOURCE);

		try {

			String currentDateTimeSofia = LocalDateTime.now(ZoneId.of(Defs.DATETIME_TIMEZONE_SOFIA))
			        .format(DateTimeFormatter.ofPattern(DATE_FORMAT)).toString();

			Date updateDate = DateTimeUtils.parseDate(currentDateTimeSofia, DATE_FORMAT);

			// Parse table with currencies
			Element span = doc.select("tbody > tr.bitcoin").get(0);
			htmlData = span.toString();
			CurrencyData currencyData = new CurrencyData();
			currencyData.setCode(Defs.BITCOINS);
			currencyData.setBuy(span.child(1).text());
			currencyData.setSell(span.child(2).text());
			currencyData.setRatio(1);
			currencyData.setSource(Sources.CRYPTO.getID());
			currencyData.setDate(updateDate);
			result.add(currencyData);

			return normalizeCurrencyData(result);
		} catch (RuntimeException e) {
			throw new IOException(e);
		}
	}

	@Override
	public void getRates(Callback callback) throws SourceException {
		try {
			doGet(URL_SOURCE, new HTTPCallback() {

				@Override
				public void onRequestFailed(Exception e) {
					getReporter().write(TAG_NAME, "Connection failure= {}", ExceptionUtils.getStackTrace(e));

					CryptoBGSource.this.close();
					callback.onFailed(e);
				}

				@Override
				public void onRequestCompleted(HttpResponse response, boolean isCanceled) {
					List<CurrencyData> result = Lists.newArrayList();

					if (!isCanceled) {
						try {

							result = getCryptoRates(response.getEntity().getContent());
						} catch (IOException | ParseException e) {
							log.error("Could not parse source data!", e);
							getReporter().write(TAG_NAME, "Parse failed= {}  HTML= {}", ExceptionUtils.getStackTrace(e),
			                        htmlData);
						}
					} else {
						log.warn("Request was canceled! No currencies were downloaded.");
						getReporter().write(TAG_NAME, "Request was canceled! No currencies were downloaded.");
					}

					CryptoBGSource.this.close();
					callback.onCompleted(result);
				}
			});
		} catch (URISyntaxException e) {
			throw new SourceException("Invalid source url - " + URL_SOURCE, e);
		}

	}

	@Override
	public String getName() {
		return TAG_NAME;
	}

}

@@ -1339,50 +1339,8 @@
 r);%0A
-%09%09// TODO Auto-generated constructor stub%0A
 %09%7D%0A%0A
@@ -1359,21 +1359,25 @@
 nsforms 
-Tavex
+Crypto BG
  HTML da
@@ -1725,16 +1725,58 @@
 SOURCE);
+%0A%09%09htmlData = doc.toString(); // debugging
 %0A%0A%09%09try 
@@ -1777,17 +1777,16 @@
 %09%09try %7B%0A
-%0A
 %09%09%09Strin
@@ -2122,39 +2122,8 @@
 0);%0A
-%09%09%09htmlData = span.toString();%0A
 %09%09%09C
@@ -3372,32 +3372,20 @@
 (e),%0A%09%09%09
-                
+%09%09%09%09
         

Add debug statement for the complete document downloaded from crypto bg