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

"""
Парсим данные по биткойнам от бирж.
"""
from __future__ import print_function

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


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


class UniversalJsonParser(JSONParser):

    def __init__(self, tree=None, node=None, source=None, config=None):
        self.multi_http = False
        self.array_path = None
        self.fixed_currency_id = None
        self.currency_id = None
        self.currency_value = None
        self.currency_date = None
        self.currency_timestamp = None
        self.currency_second_value = None
        self.lotsize = None

        super().__init__(tree, node, source, config)

        if config is not None:
            self.config = config
            self.multi_http = config.get("multi-http", False)
            self.array_path = config.get("array-path", "")
            self.fixed_currency_id = config.get("fixed-currency", "")
            self.currency_id = config.get("currency-id", "Code")
            self.currency_value = config.get("currency-value", "Rate")
            self.currency_timestamp = config.get("currency-timestamp", "")
            self.currency_date = config.get("currency-date", "Date")
            self.currency_second_value = config.get("currency-second-value", "")
            self.lotsize = config.get("lotsize")

    def makeConfig(self):
        JSONParser.makeConfig(self)
        self.multi_http = self.readBool("", "multi-http", False)
        self.array_path = self.readString("", "array-path", "")
        self.fixed_currency_id = self.readString("", "fixed-currency", "")
        self.currency_id = self.readString("", "currency-id", "Code")
        self.currency_value = self.readString("", "currency-value", "Rate")
        self.currency_timestamp = self.readString("", "currency-timestamp", "")
        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)
        if self.multi_http:
            for name, data in self.data.items():
                yield from self.data_parse(json.loads(data))
        else:
            yield from self.data_parse(self.data)

    def data_parse(self, data):
        quotes_array = get_field(data, self.array_path, safe=True)
        try:
            iter(quotes_array)
        except TypeError:
            raise Exception("Quotes object is not array")
        for quote in quotes_array:
            try:
                currency_id = get_field(quote, self.currency_id) if not self.fixed_currency_id else self.fixed_currency_id
                currency_value = get_field(quote, self.currency_value)

                if self.default_map.get_quote_param(currency_id, 'use_source_lotsize'):
                    lotsize = get_field(quote, self.lotsize)
                    if lotsize != 1:
                        currency_value = currency_value / float(lotsize)

                currency_second_value = None
                if self.currency_second_value:
                    currency_second_value = get_field(quote, self.currency_second_value)
                if currency_value:
                    currency_value = round(float(currency_value), DB_PRECISION)
                    if self.currency_timestamp != "":
                        currency_timestamp = get_field(quote, self.currency_timestamp)
                        strtz = get_timezone(self.source, self.source)
                        currency_date = datetime.fromtimestamp(currency_timestamp, tz=pytz.timezone(strtz))
                        price = self.default_map.make_price(currency_id, currency_date, currency_value)
                        if price is not None:
                            yield price
                    else:
                        currency_date = get_field(quote, self.currency_date)
                        price = self.default_map.make_price_date(currency_id, currency_date, currency_value)
                        if price is not None:
                            yield price
                if currency_second_value is not None:
                    currency_value = round(float(currency_second_value), DB_PRECISION)
                    if self.currency_timestamp != "":
                        currency_timestamp = get_field(quote, self.currency_timestamp)
                        strtz = get_timezone(self.source, self.source)
                        currency_date = datetime.fromtimestamp(currency_timestamp, tz=pytz.timezone(strtz))
                        price = self.default_map.make_price(currency_id + '_second', currency_date, currency_value)
                        if price is not None:
                            yield price
                    else:
                        currency_date = get_field(quote, self.currency_date)
                        price = self.default_map.make_price_date(currency_id + '_second', currency_date, currency_value)
                        if price is not None:
                            yield price
            except Exception as e:
                raise e


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