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

"""
JSON экспорт котировок для морды
"""
from __future__ import print_function
from stocks3.export.templater import Templater
from stocks3.core.factories import templaters
import json
from stocks3.share.db import WithDB


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


class ExJsonTemplater(Templater, WithDB):
    def __init__(self, tree, node, exporter, calculator):
        self.filename_template = ''
        self.price_store = []
        self.filename = ''
        self.output_count = None
        self.hist_count = None

        Templater.__init__(self, tree, node, exporter, calculator)
        WithDB.__init__(self)
        # FIXME: init вызывается после makeConfig o_O

    def makeConfig(self):
        Templater.makeConfig(self)
        self.filename = '{}/{}'.format(self.readString("", "output-directory"), self.readString("", "output-file"))
        self.output_count = self.readInt("", "output-count", 0) or None
        self.hist_count = self.readInt("", "hist-count", self.output_count)

    @staticmethod
    def make_price_item(quote, price, region):
        tmp = {
            'geoid': 10000 if region is None or region == 0 else region,
            'id': quote.quote_id,
            'date': price.date.strftime("%Y-%m-%d %H:%M"),
            'value': price.buy.formatted_value,
            'adelta': price.buy.absolute,
            'rdelta': ("%.2f" % float(price.buy.relative)),
            'value2': price.precision_2.buy.formatted_value,
            'adelta2': price.precision_2.buy.absolute,
            'rdelta2': price.precision_2.buy.relative,
            'value0': price.precision_0.buy.formatted_value,
            'adelta0': price.precision_0.buy.absolute,
            'rdelta0': price.precision_0.buy.relative,
            'unconfirmed': price.unconfirmed,
            'delta': price.delta_flag,
            'ishot': price.is_hot,
        }
        if price.quote.numerator.scale != 1:
            tmp['nscale'] = price.quote.numerator.scale
        if price.quote.denominator.scale != 1:
            tmp['dscale'] = price.quote.denominator.scale
        if price.is_dual_price:
            tmp['sell_value'] = price.sell.formatted_value
            tmp['sell_adelta'] = price.sell.absolute
            tmp['sell_rdelta'] = ("%.2f" % float(price.sell.relative))
            tmp['sell_value2'] = price.precision_2.sell.formatted_value
            tmp['sell_adelta2'] = price.precision_2.sell.absolute
            tmp['sell_rdelta2'] = price.precision_2.sell.relative
            tmp['sell_value0'] = price.precision_0.sell.formatted_value
            tmp['sell_adelta0'] = price.precision_0.sell.absolute
            tmp['sell_rdelta0'] = price.precision_0.sell.relative
        if not price.drop_unixtime:
            tmp['unixtime'] = int(price.unixtime)
        return tmp

    def push(self, quote, data):
        for region, prices in data.items():
            if self.output_count:
                prices = prices[:self.output_count]
            if len(prices) < 1:
                continue

            for price in prices:
                self.price_store.append(self.make_price_item(quote, price, region))

    def flush(self):
        try:
            with open(self.filename, 'w') as f:
                f.write(json.dumps({
                    'stocks': self.price_store,
                }))
        except Exception as e:
            print('Error while writing results', e)
            print('filename - ', self.filename)


templaters.register("stocks3.templaters.exJSON", ExJsonTemplater)
