# -*- coding: utf-8 -*-
"""
Разбираем курсы центрального банка египта.
"""
import html.parser
from stocks3.core.parser import Parser
from stocks3.core.place import FilePlace
from stocks3.core.factories import parsers


class NasdaqComHtmlParser(html.parser.HTMLParser):
    def __init__(self):
        html.parser.HTMLParser.__init__(self, convert_charrefs=True)
        self._curr_data = {}  # current table line parsed data

        self._in_data_table = False
        self._in_table_n = 0
        self._data_table_lno = 0  # line number counter
        self._data_table_cno = 0  # column number counter
        self._in_td_elem = False  # if we are in cbe data table td element

        self.result = {
            'dates': [],
        }

    def handle_starttag(self, tag, attrs):
        if tag == 'table':
            self._in_table_n += 1
            if 2 == self._in_table_n:
                self._in_data_table = True
        if self._in_data_table:
            if tag == 'tr':  # increase line number counter
                self._data_table_lno += 1
                self._data_table_cno = 0
            if tag == 'td':
                self._data_table_cno += 1
                self._in_td_elem = True

    def handle_endtag(self, tag):
        if self._in_data_table:
            if tag == 'table':
                self._in_data_table = False
            if tag == 'td':
                self._in_td_elem = False
            if tag == 'tr':
                if 1 in self._curr_data:
                    quote = {
                        'date': self._curr_data[1],
                        'value': self._curr_data[2],
                    }
                    self.result['dates'].append(quote)
                self._data_table_cno = 0

    def handle_data(self, data):
        if self._in_data_table:
            if self._in_td_elem:
                self._curr_data[self._data_table_cno] = data

    def parse(self, content):
        self.feed(content)

    def error(self, message):
        pass


class NasdaqComParser(Parser):
    places = [FilePlace]

    def parse(self, place):
        parser = NasdaqComHtmlParser()
        parser.parse(place.read())

        for quote_data in parser.result['dates'][:5]:
            # print(self._curr_data)

            source_date = quote_data['date']
            quote_data['value'] = float(quote_data['value'])
            try:
                price = self.default_map.make_price_date('YNDX', source_date, quote_data['value'])
                if price is not None:
                    yield price
            except Exception:
                return None


parsers.register("stocks3.parsers.NasdaqCom", NasdaqComParser)
