# -*- 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 CbeEgyptHTMLParser(html.parser.HTMLParser):
    def __init__(self):
        html.parser.HTMLParser.__init__(self, convert_charrefs=True)
        self._curr_data = {}  # current table line parsed data

        self._in_cbe_data_table = False
        self._in_cbe_table_n = 0
        self._cbe_data_table_lno = 0  # line number counter
        self._cbe_data_table_cno = 0  # column number counter
        self._in_td_elem = False  # if we are in cbe data table td element

        self.result = {
            'date': '',
            'quotes': [],
        }

    def handle_starttag(self, tag, attrs):
        if tag == 'table':
            self._in_cbe_table_n += 1
            if 6 == self._in_cbe_table_n:
                self._in_cbe_data_table = True
        if self._in_cbe_data_table:
            if tag == 'tr':  # increase line number counter
                self._cbe_data_table_lno += 1
                self._cbe_data_table_cno = 0
            if tag == 'td':
                self._cbe_data_table_cno += 1
                self._in_td_elem = True

    def handle_endtag(self, tag):
        if self._in_cbe_data_table:
            if tag == 'table':
                self._in_cbe_data_table = False
            if tag == 'td':
                self._in_td_elem = False
            if tag == 'tr':
                if self._cbe_data_table_cno == 0:
                    self.result['date'] = self._curr_data[1]
                if self._cbe_data_table_cno > 0:
                    self.result['quotes'].append({
                        'quote_name': self._curr_data[1].replace('\u200b', '').strip(),
                        'sell_value': self._curr_data[2],
                        'buy_value': self._curr_data[3],
                    })

                self._cbe_data_table_cno = 0

    def handle_data(self, data):
        if self._in_cbe_data_table:
            if self._in_td_elem:
                self._curr_data[self._cbe_data_table_cno] = data

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

    def error(self, message):
        pass


class CbeEgyptParser(Parser):
    places = [FilePlace]

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

        source_date = parser.result['date']
        for quote_data in parser.result['quotes']:
            quote_data['buy_value'] = float(quote_data['buy_value'])
            quote_data['sell_value'] = float(quote_data['sell_value'])
            quote_name = quote_data['quote_name'][:-3]
            price = self.default_map.make_dual_price_date(quote_name, source_date,
                                                          quote_data['buy_value'], quote_data['sell_value'])
            if price is not None:
                yield price


parsers.register("stocks3.parsers.cbe_egypt", CbeEgyptParser)
