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

"""
Парсим данные Fxclub.
"""
from __future__ import print_function

import json
from stocks3.core.factories import parsers
from stocks3.parsers.jsonp import JSONParser
from stocks3.share.db import DB_PRECISION
from stocks3.core.common import get_field

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


class ForexclubJsonParser(JSONParser):

    def __init__(self, tree, node, source):
        self.array_path = None
        self.currency_id = None
        self.currency_value = None
        self.currency_date = None
        self.currency_second_value = None
        super().__init__(tree, node, source)

    def makeConfig(self):
        JSONParser.makeConfig(self)
        self.array_path = self.readString("", "array-path", "")
        self.currency_id = self.readString("", "currency-id", "Code")
        self.currency_value = self.readString("", "currency-value", "Rate")
        self.currency_date = self.readString("", "currency-date", "Date")
        self.currency_second_value = self.readString("", "currency-second-value", "")

    def parse(self, place):
        JSONParser.parse(self, place)
        quotes_array = get_field(self.data, self.array_path, safe=True)
        for quote_name, quote_description in quotes_array.items():
            try:
                currency_id = quote_name
                quote = json.loads(quote_description)
                currency_value = get_field(quote, "Result.RateHistory")[-1]['c']
                currency_date = get_field(quote, "Result.RateHistory")[-1]['dt']
                if currency_value:
                    currency_value = round(float(currency_value), DB_PRECISION)
                    mp = self.maps[quote_name]
                    price = mp.make_price_date(currency_id, currency_date, currency_value)
                    if price is not None:
                        yield price
            except Exception as e:
                raise e


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