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

"""
JSON экспорт котировок для графиков на highcharts
"""
from __future__ import print_function

from yt.wrapper import YtClient

from stocks3.core.factories import templaters
from stocks3.export.templater import Templater
from stocks3.share.timezone import get_timezone_fixed
from stocks3.core.config import JSONConfigurable

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


def sign(num):
    return 1 if num >= 0 else -1


class YtTemplater(Templater, JSONConfigurable):
    def __init__(self, tree, node, exporter, calculator):
        JSONConfigurable.__init__(self)
        self.yt_token = self.read_item("yt_token", "")
        self.environment = self.read_item("env", "testing")
        self.output_table = ""
        self.output_table_buffer = ""
        Templater.__init__(self, tree, node, exporter, calculator)
        self.price_store = []

    def makeConfig(self):
        Templater.makeConfig(self)
        self.output_table = self.readString("", "output-table")
        if self.environment == "testing":
            self.output_table += "_testing"
        self.output_table_buffer = self.output_table + "_buffer"

    def push(self, quote, data):
        quote_id = quote.quote_id
        tz = get_timezone_fixed(quote, quote.source)
        # offset = datetime.now(pytz.timezone(tz)).strftime('%z')
        # offset_hours = str(int(offset[0:3]))
        # offset_minutes = str(sign(int(offset[0:3])) * int(offset[3:]))

        for region, prices in data.items():
            if region is None:
                print('Alarm!!')
            region = 10000 if region is None or region == 0 else int(region)
            for price in prices:
                self.price_store.append({
                    'quote_id': int(quote_id),
                    'region': int(region),
                    'tzname': tz,
                    'unixtime': int(price.date.strftime("%s")),
                    'is_dual': price.is_dual_price,
                    'buy': price.buy.value,
                    'sell': price.sell.value if price.is_dual_price else None,
                    'unconfirmed': price.unconfirmed,
                    'source_id': int(quote.source.source_inner_id),
                })

    def flush(self):
        yt_client = YtClient(proxy='hahn', config={'tabular_data_format': 'json'}, token=self.yt_token)
        schema = [
            {'name': 'quote_id', 'type': 'uint32'},
            {'name': 'region', 'type': 'uint32'},
            {'name': 'tzname', 'type': 'string'},
            {'name': 'unixtime', 'type': 'uint64'},
            {'name': 'is_dual', 'type': 'boolean'},
            {'name': 'buy', 'type': 'float'},
            {'name': 'sell', 'type': 'float'},
            {'name': 'unconfirmed', 'type': 'boolean'},
            {'name': 'source_id', 'type': 'uint32'},
        ]
        try:
            numbered_output_table_buffer = self.output_table_buffer + "_1"
            if yt_client.exists(self.output_table):
                table_link_location = yt_client.get("{}/@path".format(self.output_table))
                if table_link_location == self.output_table_buffer + "_1":
                    numbered_output_table_buffer = self.output_table_buffer + "_2"

            if yt_client.exists(numbered_output_table_buffer):
                yt_client.remove(numbered_output_table_buffer)

            yt_client.create('table', numbered_output_table_buffer, attributes={'schema': schema})

            yt_client.write_table(numbered_output_table_buffer, self.price_store)
            yt_client.link(numbered_output_table_buffer, self.output_table, force=True)

        except Exception as e:
            print('Error while writing results', e)
            print('filename - ', self.filename_template)


templaters.register("stocks3.templaters.YT", YtTemplater)
