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

"""
Парсер для ecopress_by.
"""
import json
from stocks3.core.parser import Parser
from stocks3.core.factories import parsers
from stocks3.core.config import parse_xml_fromstring
from datetime import datetime
from stocks3.share.db import DB_PRECISION


class EcopressParser(Parser):

    def parse(self, place):
        Parser.parse(self, place)

        content = json.loads(place.read())
        for mapname, f in content.items():
            tree = parse_xml_fromstring(f)
            root = tree.getroot()
            mp = self.maps[mapname]
            unixtime = float(root.find("%s/bestvalues/date_timestamp" % mapname).text)
            date = datetime.fromtimestamp(unixtime)
            for item in root.findall("%s/bestvalues/stock" % mapname):
                sourceQuoteId = item.attrib["id"]
                buy_value = float(item.find("sell").text)
                sell_value = float(item.find("buy").text)
                price = mp.make_dual_price(sourceQuoteId, date,
                                           round(buy_value, DB_PRECISION),
                                           round(sell_value, DB_PRECISION))
                if price is not None:
                    yield price


parsers.register("stocks3.parsers.Ecopress", EcopressParser)


