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

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

import json
import os
from datetime import datetime, timedelta

import pytz

from stocks3.core.factories import templaters
from stocks3.core.sharedregion import SHARED_REGION
from stocks3.export.templater import Templater
from stocks3.share.savethroughtmp import save_through_tmp
from stocks3.share.timezone import get_timezone_fixed, get_active_timezones

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


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


class HighchartsTemplater(Templater):
    def __init__(self, tree, node, exporter, calculator):
        Templater.__init__(self, tree, node, exporter, calculator)
        self.price_store = {}
        # Структура regions => quote_id => список котировок

        # FIXME: init вызывается после makeConfig o_O
        # self.filename_template = ''
        # self.filename = ''

    def makeConfig(self):
        Templater.makeConfig(self)
        self.output_directory = self.readString("", "output-directory")
        self.filename_template = self.readString("", "filename-template")
        self.filename_template_2 = self.readString("", "filename-template-2")

    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:]))

        if quote_id not in self.price_store:
            self.price_store[quote_id] = {
                'tzname': tz,
                'tzoffset_hours': offset_hours,
                'tzoffset_minutes': offset_minutes,
                'prices': {},
            }
        for region, prices in data.items():
            if region is None:
                print('Alarm!!')
            region = 10000 if region is None or region == 0 else int(region)
            result_prices = []
            is_dual = False
            for price in prices:
                # 19 полей в csv
                tmp = [int(price.date.strftime("%s")) * 1000, price.buy.value]
                if price.is_dual_price:
                    tmp.append(price.sell.value)
                    is_dual = True
                result_prices.append(tmp)
            self.price_store[quote_id]['prices'][region] = result_prices
            self.price_store[quote_id]['legend'] = ['sell', 'buy'] if is_dual else ['buy']

    def gen_filename(self, filename_template, quote_id, region=None):
        """
        Возвращает имя выходного файла для котировки quote и региона region.
        """
        filename = filename_template.format(region=str(region), id=str(quote_id))
        if region is None or region == SHARED_REGION or region == 10000:
            # Здесь мы просто срезаем все папки, оставляя только имя файла.
            return os.path.basename(filename)
        else:
            return filename

    def flush(self):
        try:
            pass
            for quote_id, quote_container in self.price_store.items():
                for region, prices in quote_container['prices'].items():
                    save_through_tmp(self.output_directory,
                                     self.gen_filename(self.filename_template, quote_id, region),
                                     json.dumps({
                                         'tzname': quote_container['tzname'],
                                         'tzoffset_hours': quote_container['tzoffset_hours'],
                                         'tzoffset_minutes': quote_container['tzoffset_minutes'],
                                         'prices': prices,
                                         'legend': quote_container['legend'],
                                     }))
                    min_prices = [price for price in prices
                                  if datetime.fromtimestamp(price[0]/1000) > datetime.now() - timedelta(days=365)]
                    save_through_tmp(self.output_directory,
                                     self.gen_filename(self.filename_template_2, quote_id, region),
                                     json.dumps({
                                         'tzname': quote_container['tzname'],
                                         'tzoffset_hours': quote_container['tzoffset_hours'],
                                         'tzoffset_minutes': quote_container['tzoffset_minutes'],
                                         'prices': min_prices,
                                         'legend': quote_container['legend'],
                                     }))
        except Exception as e:
            print('Error while writing results', e)
            print('filename - ', self.filename_template)


templaters.register("stocks3.templaters.Highcharts", HighchartsTemplater)
