# -*- 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 BitcoinParser(JSONParser):
    def makeConfig(self):
        JSONParser.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):
        JSONParser.parse(self, place)

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


parsers.register("stocks3.parsers.Bitcoin", BitcoinParser)
