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

"""
Штука для сохранения кросскурсов.
"""

import json

from stocks3.core.factories import parsers
from stocks3.core.parser import Parser
from datetime import datetime
from stocks3.core.common import is_number

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


class CrossesParser(Parser):
    def __init__(self, tree, root, source):
        self.data = ''
        Parser.__init__(self, tree, root, source)

    def makeConfig(self):
        Parser.makeConfig(self)

    def parse(self, place):
        Parser.parse(self, place)
        self.data = place.read()
        for cross in json.loads(self.data):
            quote_num = cross['num']
            quote_res = cross['res']
            # цена 1
            if 'den' in cross:
                quote_den = cross['den']
                pr1 = self.source.saver.db.select_prices(self.quotes_config.getQuote(quote_den), 0, 1)[0]['value']
                if is_number(quote_num):
                    pr2 = float(quote_num)
                else:
                    pr2 = self.source.saver.db.select_prices(self.quotes_config.getQuote(quote_num), 0, 1)[0]['value']
                value = pr2 / pr1
                date1 = datetime.strptime(self.source.saver.db.select_prices(
                    self.quotes_config.getQuote(quote_den), 0, 1)[0]['date'], "%Y-%m-%d")
            elif 'num2' in cross:
                quote_num2 = cross['num2']
                pr1 = self.source.saver.db.select_prices(self.quotes_config.getQuote(quote_num), 0, 1)[0]['value']
                pr2 = self.source.saver.db.select_prices(self.quotes_config.getQuote(quote_num2), 0, 1)[0]['value']
                value = pr1 * pr2
                date1 = datetime.strptime(self.source.saver.db.select_prices(
                    self.quotes_config.getQuote(quote_num2), 0, 1)[0]['date'], "%Y-%m-%d")
            else:
                raise Exception('Bad cross config!')

            if is_number(quote_num):
                date = date1
            else:
                date2 = datetime.strptime(
                    self.source.saver.db.select_prices(self.quotes_config.getQuote(quote_num), 0, 1)[0]['date'], "%Y-%m-%d")
                if date1 < date2:
                    date = date1
                else:
                    date = date2

            price = self.default_map.make_price(quote_res, date, value)
            if price is not None:
                yield price


parsers.register("stocks3.parsers.CrossesParser", CrossesParser)
