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

"""
Парсим данные от ds.ifx.ru.
"""
import json
from stocks3.core.parser import Parser
from stocks3.core.factories import parsers
from stocks3.core.config import parse_xml_fromstring


class DsIfxRuParser(Parser):

    def 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]
            for item in root.findall("ITEM"):
                source_quote_id = item.attrib["id"] if "id" in item.attrib else item.attrib["ENickName"]
                if "rate" in item.attrib:
                    rate = item.attrib["rate"]
                elif "ClosePrice" in item.attrib:
                    rate = item.attrib["ClosePrice"]
                else:
                    rate = item.attrib["LastBid"]
                value = float(rate.replace(",", "."))
                source_date = item.attrib["date"]
                if "time" in item.attrib and not mp.useClosetime(source_quote_id):
                    source_date += ' ' + item.attrib["time"]
                    use_closetime = False
                else:
                    use_closetime = True
                # Есть возможность отображат по nickname
                if mp.get_quote_param(source_quote_id, 'use_source_lotsize'):
                    lotsize = int(item.attrib["lotsize"])
                    if lotsize:
                        value /= lotsize
                price = mp.make_price_date(source_quote_id, source_date, value, use_closetime)
                if price is not None:
                    yield price


parsers.register("stocks3.parsers.DsIfxRu", DsIfxRuParser)


