# -*- coding: utf-8 -*-
"""
Разбираем ставку рефинансирования.
"""
from __future__ import print_function
from datetime import datetime
import html.parser
from stocks3.core.parser import Parser
from stocks3.core.place import MongoPlace
from stocks3.core.factories import parsers


class BoeHTMLParser(html.parser.HTMLParser):
    def __init__(self):
        html.parser.HTMLParser.__init__(self, convert_charrefs=True)
        self._tables = []
        self._table_depth = 0
        self._in_th = False
        self._in_td = False

    def handle_starttag(self, tag, attrs):
        if tag == 'table':
            self._tables.append({})
            self._table_depth += 1

        if self._table_depth > 0:
            if tag == 'tr':
                if 'rows' not in self._tables[-1]:
                    self._tables[-1]['rows'] = [[]]
                else:
                    self._tables[-1]['rows'].append([])
            if tag == 'td' or tag == 'th':
                self._in_td = True
                if tag == 'th':
                    self._in_th = True
                self._tables[-1]['rows'][-1].append({})

    def handle_endtag(self, tag):
        if tag == 'table':
            self._table_depth -= 1
        if tag == 'tr':
            pass
        if tag == 'td' or tag == 'th':
            self._in_td = False
            if tag == 'th':
                self._in_th = False

    def handle_data(self, tagdata):
        if self._table_depth > 0:
            if self._in_td:
                if self._in_th:
                    self._tables[-1]['rows'][-1][-1] = {
                        "header": True,
                        "value": tagdata.strip(),
                    }
                else:
                    self._tables[-1]['rows'][-1][-1] = {
                        "value": tagdata.strip(),
                    }

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

    def get_data(self):
        return self._tables


class BankofenglandParser(Parser):
    places = [MongoPlace]

    def parse(self, place):
        parser = BoeHTMLParser()
        parser.parse(place.read())
        tables = parser.get_data()
        if len(tables) < 1 or 'rows' not in tables[0]:
            raise "Could not found tables in BOE answer"

        if len(tables) < 2 or 'rows' not in tables[0]:
            return []

        currency_table = tables[0]['rows']
        source_date = currency_table[0][1]['value']
        for data in currency_table[1:]:
            quote_name = data[0]['value']
            value = float(data[1]['value'])
            price = self.default_map.make_price_date(quote_name, source_date, value)
            if price is not None:
                yield price


parsers.register("stocks3.parsers.Bankofengland", BankofenglandParser)
