# -*- coding: utf-8 -*-
"""
Парсер для Kase.kz.
"""
import html.parser

from stocks3.core.parser import Parser
from stocks3.core.factories import parsers

__author__ = "Zasimov Alexey"
__email__ = "zasimov-a@yandex-team.ru"


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

        self.tables = []
        self.current_table = 0
        self.current_row = 0
        self.current_cell = 0
        self.in_cell = False

    def handle_starttag(self, tag, attrs):
        if tag == 'table':
            self.current_row = 0
            self.current_cell = 0
            self.tables.append([])
        if tag == 'tr':  # increase line number counter
            self.current_cell = 0
            self.tables[self.current_table].append([])
        if tag == 'td' or tag == 'th':
            self.tables[self.current_table][self.current_row].append('')
            self.in_cell = True

    def handle_endtag(self, tag):
        if tag == 'table':
            self.current_table +=1
        if tag == 'tr':
            self.current_row += 1
        if tag == 'td' or tag == 'th':
            self.current_cell += 1
            self.in_cell = False

    def handle_data(self, data):
        if self.in_cell:
            self.tables[self.current_table][self.current_row][self.current_cell] = data

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

    def error(self, message):
        pass


class KaseKzParser(Parser):
    def parse(self, place):
        f = place.read()
        parser = KasekzHTMLParser()
        parser.parse(place.read())
        try:
            if len(parser.tables) and len(parser.tables[0]) > 1:
                value = parser.tables[0][1][4]
                value = float(value.replace(' ', '').replace(',', '.'))
                source_date = parser.tables[0][1][0]
                price = self.default_map.make_price_date("all", source_date, value)
                if price is not None:
                    yield price
        except Exception as e:
            raise e


parsers.register("stocks3.parsers.KaseKz", KaseKzParser)
