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

"""
Генерирует файл regions.xml
"""

from __future__ import print_function
from stocks3.core.config import ConfigurationError
from stocks3.export.templater import Templater
from stocks3.core.factories import templaters
__author__ = "Bogdanov I Evgeniy"
__email__ = "evbogdanov@yandex-team.ru"


class RegionsTemplater(Templater):
    TEMPFILE_SUFFIX = "stocks3_item_templater"

    def __init__(self, tree, node, exporter, calculator):
        self.regions = {}
        Templater.__init__(self, tree, node, exporter, calculator)

    def makeConfig(self):
        Templater.makeConfig(self)
        if self.output_file is None:
            raise ConfigurationError("Parameter .output-file is not defined.")
        self.output_count = self.readInt("", "output-count", 0) or None

    def push(self, quote, data):
        for region_, prices in data.items():
            if len(prices) < 2:
                continue
            region = str(int(region_))
            if quote.quote_id not in self.regions:
                self.regions[quote.quote_id] = [region]
            else:
                self.regions[quote.quote_id].append(region)

    def flush(self):
        """
        В этом методе все данные накопленные через push сбрасываются на диск
        @return: None
        """
        r = []
        for quoteId in self.regions:
            r.append({
                'quote_id': quoteId,
                'region_list': ", ".join(sorted(self.regions[quoteId], key=lambda x: int(x)))
            })
        ns = self.make_default_env()
        ns.update({"regions": r})
        self.save_through_tmp(ns, self.output_file)

templaters.register("stocks3.templaters.Regions", RegionsTemplater)


