# -*- coding: utf-8 -*-
from __future__ import print_function
from stocks3.parsers.jsonp import JSONParser
from stocks3.core.factories import parsers
from stocks3.share.db import DB_PRECISION

__author__ = "Bogdanov Evgeniy"
__email__ = "evbogdanov@yandex-team.ru"


class KursKzParser(JSONParser):
    def __init__(self, tree, node, source):
        JSONParser.__init__(self, tree, node, source)

    def makeConfig(self):
        JSONParser.makeConfig(self)
        self.regions_map = {}
        for region_node in self.node.findall("regions-map/region"):
            from_ = region_node.attrib["from"]
            to = int(region_node.attrib["to"])
            if from_ in self.regions_map:
                self.regions_map[from_].append(to)
            else:
                self.regions_map[from_] = [to]

    def parse(self, place):
        JSONParser.parse(self, place)

        source_date = str(self.datatree['time']['updatedISO']).split('+')[0]
        for region, data in self.datatree.items():
            if region not in self.regions_map:
                continue
            for key, value in data.items():
                source_quote_id = value["code"]
                try:
                    if value['sale'] is None or value['purchase'] is None:
                        continue
                    buy_value = value['sale']
                    buy_value = round(float(buy_value), DB_PRECISION)
                    sell_value = value['purchase']
                    sell_value = round(float(sell_value), DB_PRECISION)
                except KeyError:
                    # FIXME: очень трудно будет понять, почему не работает парсер
                    continue
                if region in self.regions_map:
                    for result_region in self.regions_map[region]:
                        price = self.default_map.make_dual_price_date(source_quote_id, source_date, buy_value, sell_value)
                        if price is not None:
                            price.onlyForRegion(result_region)
                            yield price


parsers.register("stocks3.parsers.KursKz", KursKzParser)
