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

"""
Данные о золоте по турции
"""
from __future__ import print_function
__author__ = "Bogdanov Evgeniy"
__email__ = "evbogdanov@yandex-team.ru"

from stocks3.parsers.jsonp import JSONParser
from stocks3.core.factories import parsers
from stocks3.share.db import DB_PRECISION
from stocks3.share.timezone import get_timezone
from datetime import datetime
import pytz


class DovizGoldParser(JSONParser):

    def __init__(self, tree, node, source):
        JSONParser.__init__(self, tree, node, source)
        self.tags = {}

    def makeConfig(self):
        JSONParser.makeConfig(self)

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

        for quote in self.datatree:
            source_quote_id = str(quote["name"])
            strtz = get_timezone(self.source, self.source)
            source_date = datetime.fromtimestamp(quote["update_date"], tz=pytz.timezone(strtz))
            try:
                buy_value = quote["selling"]
                sell_value = quote["buying"]
            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(source_quote_id, source_date, buy_value, sell_value)
            if price is not None:
                yield price


parsers.register("stocks3.parsers.DovizGold", DovizGoldParser)

