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

"""
Парсим турецкий сайт с валютами - tcmb.gov.tr.
"""

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

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


class TcmbGovTrParser(XMLParser):

    def makeConfig(self):
        XMLParser.makeConfig(self)
        self.tags = {}
        for tag in self.node.findall("tags/tag"):
            self.tags[tag.attrib["id"]] = {"buy": tag.attrib["buy"],
                                           "sell": tag.attrib["sell"]}

    def parse(self, place):
        XMLParser.parse(self, place)
        sourceDate = self.dataRoot.attrib["Tarih"]
        for node in self.dataRoot.findall("Currency"):
            sourceQuoteId = node.attrib["CurrencyCode"]
            try:
                buy_value = node.find(self.tags[sourceQuoteId]["sell"]).text
                sell_value = node.find(self.tags[sourceQuoteId]["buy"]).text
            except KeyError:
                # FIXME: очень трудно будет понять, почему не работает парсер
                continue
            buy_value = round(float(buy_value), DB_PRECISION)
            sell_value = round(float(sell_value), DB_PRECISION)
            price = self.default_map.make_dual_price_date(sourceQuoteId, sourceDate, buy_value, sell_value)
            if price is not None:
                yield price


parsers.register("stocks3.parsers.TcmbGovTr", TcmbGovTrParser)

