# -*- coding: utf-8 -*-
"""
Разбираем ставку рефинансирования.
"""

import html.parser
from stocks3.core.parser import Parser
from stocks3.core.place import MongoPlace
from stocks3.core.factories import parsers


# class for parsing html data
class BiCurHTMLParser(html.parser.HTMLParser):

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

        self._in_cbr_data_table = False
        self._in_cbr_table_n = 0
        self._cbr_data_table_lno = 0  # line number counter
        self._cbr_data_table_cno = 0  # column number counter
        self._in_td_elem = False  # if we are in cbr data table td element

        self.result = {}

    def handle_starttag(self, tag, attrs):
        if tag == 'table':
            self._in_cbr_table_n += 1
            if 1 == self._in_cbr_table_n:
                self._in_cbr_data_table = True
        if self._in_cbr_data_table:
            if tag == 'tr':  # increase line number counter
                self._cbr_data_table_lno += 1
                self._cbr_data_table_cno = 0
            if tag == 'td':
                self._cbr_data_table_cno += 1
                self._in_td_elem = True

    def handle_endtag(self, tag):
        if self._in_cbr_data_table:
            if tag == 'table':
                self._in_cbr_data_table = False
            if tag == 'td':
                self._in_td_elem = False
            if tag == 'tr':
                if self._cbr_data_table_cno > 0:
                    self.result['date'] = self._curr_data[1]
                    self.result['value'] = self._curr_data[2].replace(',', '.')
                self._cbr_data_table_cno = 0

    def handle_data(self, data):
        if self._in_cbr_data_table:
            if self._in_td_elem:
                self._curr_data[self._cbr_data_table_cno] = data

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

    def error(self, message):
        pass


class CbrBiCurParser(Parser):
    places = [MongoPlace]

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

        source_date = parser.result['date']
        value = float(parser.result['value'])
        price = self.default_map.make_price_date('all', source_date, value)
        if price is not None:
            yield price


parsers.register("stocks3.parsers.CbrBiCur", CbrBiCurParser)

