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

"""
Сохранение информации о котировках в виде Prepared-XML.
"""

from __future__ import with_statement, print_function
from stocks3.core.factories import savers
from stocks3.core.saver import Saver
from stocks3.share.forxml import minimize, tidylib
__author__ = "Zasimov Alexey"
__email__ = "zasimov-a@yandex-team.ru"


class Prepared(Saver):

    DEFAULT_TEMPLATE = "tmpl/prepared.xml"
    PREFIX = "data/prepare/"
    SUFFIX = ".prepare.data.xml"

    def __init__(self, tree, node, source):
        Saver.__init__(self, tree, node, source)
        self.prices = []

    def _default_output(self):
        """
        Конструирует имя целевого файла, если это имя не указано в параметрах
        Saver'a.
        Работает просто: PREFIX + source.id + SUFFIX
        """
        return self.PREFIX + self.source.sourceId + self.SUFFIX

    def makeConfig(self):
        self.filename = self.readString("", "template", self.DEFAULT_TEMPLATE)
        self.output = self.readString("", "output", self._default_output())

    def save(self, price):
        Saver.save(self, price)
        self.prices.append(price)

    def _get_search_list_for_template(self):
        sl = {"prices": self.prices, "source": self.source}
        return [sl]

    def get_data(self):
        print('prepared templater call!')
        # template = cheetah_template(self.filename, self._get_search_list_for_template())
        return str(template)

    def flush(self):
        data = self.get_data()
        with open(self.output, "wb") as f:
            f.write(data)


savers.register("stocks3.savers.Prepared", Prepared)


class PreparedMini(Prepared):
    def get_data(self):
        xml = Prepared.get_data(self)
        return minimize(xml)

if tidylib is None:
    savers.register("stocks3.savers.PreparedMini", Prepared)
else:
    savers.register("stocks3.savers.PreparedMini", PreparedMini)

