# -*- coding: utf-8 -*-
""""
    Штука достает из БД данные для рассчета и генерирует кросскурсы
"""
import json

from stocks3.core.transport import Transport
from stocks3.core.factories import transports
from stocks3.share import messages


class CrossesTransport(Transport):
    def __init__(self, tree, node, source):
        self.quotes = []
        Transport.__init__(self, tree, node, source)

    def makeConfig(self):
        Transport.makeConfig(self)
        for q in self.node.findall("quotes"):
            if "quoteDen" in q.attrib:
                self.quotes.append({
                    'den': q.attrib["quoteDen"],
                    'num': q.attrib["quoteNum"],
                    'res': q.attrib["quoteRes"],
                })
            elif "quoteNum2" in q.attrib:
                self.quotes.append({
                    'num2': q.attrib["quoteNum2"],
                    'num': q.attrib["quoteNum"],
                    'res': q.attrib["quoteRes"],
                })

    def transfer(self, place):
        Transport.transfer(self, place)
        try:
            data = json.dumps(self.quotes)
            place.store(data)
        except Exception as e:
            messages.error("ERROR: %s: CrossesTransport: %s" % (self.__class__.__name__, str(e)))


transports.register("stocks3.transports.CrossesTransport", CrossesTransport)
