# -*- coding: utf-8 -*-
"""
Парсер для cbr.ru.
"""
from stocks3.parsers.xml import NewXMLParser
from stocks3.core.factories import parsers
from stocks3.core.common import get_field


class CbrReutersParser(NewXMLParser):
    def parse(self, place):
        NewXMLParser.parse(self, place)

        date = get_field(self.data,
                         'soap:Envelope.soap:Body.GetReutersCursOnDateResponse.GetReutersCursOnDateResult.'
                         'xs:schema.xs:element.@msprop:OnDate',
                         False)
        quotes_array = get_field(self.data,
                                 'soap:Envelope.soap:Body.GetReutersCursOnDateResponse.GetReutersCursOnDateResult.'
                                 'diffgr:diffgram.ReutersValutesData.Currency',
                                 True,
                                 default=[])

        for quote in quotes_array:
            value = float(quote['val']) if quote['dir'] != '1' else 1 / float(quote['val'])
            price = self.default_map.make_price_date(quote['num_code'], date, value)
            if price is not None:
                yield price


parsers.register("stocks3.parsers.CbrReuters", CbrReutersParser)
