# -*- coding: utf-8 -*-

from __future__ import print_function
"""
Разбор данных от finance.ua из нового экспорта.
"""

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


from stocks3.parsers.xml import XMLParser
from stocks3.core.factories import parsers
from stocks3.share.db import DB_PRECISION
from datetime import datetime

class FinanceUaNew(XMLParser):

    # places = [TempFiles]

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

    def parse(self, place):
        XMLParser.parse(self, place)
        sourceDate = self.dataRoot.attrib["date"].split('+')[0]
        for node in self.dataRoot.findall("currency"):
            sourceQuoteId = node.attrib["id"]
            regionId = int(node.attrib["region"])
            buy_value = node.attrib["ask"]
            sell_value = node.attrib["bid"]
            buy_value = round(float(buy_value), DB_PRECISION)
            sell_value = round(float(sell_value), DB_PRECISION)

            if (regionId in self.regions_map.keys()):
                regionId = self.regions_map[regionId]
            else:
                print('cannot find region', regionId)
                continue
            price = self.default_map.make_dual_price_date(sourceQuoteId, sourceDate, buy_value, sell_value)
            if price is not None:
                if regionId is not None:
                    price.onlyForRegion(regionId)
                yield price


parsers.register("stocks3.parsers.FinanceUaNew", FinanceUaNew)
