# -*- 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 JsonTemplater(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)
        filename = self.readString("", "output-file-v2", default="")
        if not filename:
            filename = self.readString("", "output-file")
        self.filename = '{}/{}'.format(self.readString("", "output-directory"), filename)
        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, export_additions):
        tmp = {
            'geo': 10000 if region is None or region == 0 else region,
            'id': quote.quote_id,
            'dt': price.date.strftime("%Y-%m-%d %H:%M"),
            'bv': price.buy.formatted_value,
            'bda': price.buy.absolute,
            'bdr': ("%.2f" % float(price.buy.relative)),
            'bv2': price.precision_2.buy.formatted_value,
            'bda2': price.precision_2.buy.absolute,
            'bdr2': price.precision_2.buy.relative,
            'bv0': price.precision_0.buy.formatted_value,
            'bda0': price.precision_0.buy.absolute,
            'bdr0': price.precision_0.buy.relative,
            'uc': price.unconfirmed,
            'df': 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['sv'] = price.sell.formatted_value
            tmp['sda'] = price.sell.absolute
            tmp['sdr'] = ("%.2f" % float(price.sell.relative))
            tmp['sv2'] = price.precision_2.sell.formatted_value
            tmp['sda2'] = price.precision_2.sell.absolute
            tmp['sdr2'] = price.precision_2.sell.relative
            tmp['sv0'] = price.precision_0.sell.formatted_value
            tmp['sda0'] = price.precision_0.sell.absolute
            tmp['sdr0'] = price.precision_0.sell.relative
        if not price.drop_unixtime:
            tmp['ut'] = int(price.unixtime)
        if export_additions:
            tmp['search_app_graph_base_url'] = export_additions['search_app_graph_base_url']
        return tmp

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

            export_additions = self.db.get_export_additions(quote.quote_id, region)
            # формируем первый элемент
            tmp = self.make_price_item(quote, hist_prices[0], region, export_additions)
            tmp['history'] = tuple(price.buy.formatted_value for price in prices)
            if prices[0].is_dual_price:
                tmp['shistory'] = tuple(price.sell.formatted_value for price in prices)
            self.price_store.append(tmp)

            for price in hist_prices[1:]:
                tmp = self.make_price_item(quote, price, region, export_additions)
                self.price_store.append(tmp)

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


templaters.register("stocks3.templaters.JSON", JsonTemplater)
