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

"""
Парсер данных от finam.ru.
"""
import csv

from stocks3.core.parser import Parser
from stocks3.core.place import FilePlace
from stocks3.core.factories import parsers
from stocks3.share import messages

__author__ = "Zasimov Alexey"
__email__ = "zasimov-a@yandex-team.ru"


class FinamParser(Parser):
    places = [FilePlace]

    def parse(self, place):
        data = place.read()
        reader = csv.reader(data.split('\n'), delimiter=';')
        quotes = {}
        for row in reader:
            if len(row) < 2:
                continue
            try:
                source_quote_id, period, date, time, value = row
            except ValueError as e:
                messages.error(
                    "ERROR FORMAT IGNORED: %s: finam: %s: %s" % (self.__class__.__name__, str(e), str(row)))
                continue
            source_date = date + ' ' + time
            if source_quote_id in quotes:
                if source_date > quotes[source_quote_id][0]:
                    quotes[source_quote_id] = (source_date, value)
            else:
                quotes[source_quote_id] = (source_date, value)
        for source_quote_id, (source_date, value) in quotes.items():
            try:
                price = self.default_map.make_price_date(source_quote_id, source_date, float(value))
                if price is not None:
                    yield price
            except Exception as e:
                # Игнорируем ошибки от Finam
                messages.error("ERROR IGNORED: %s: finam: %s" % (self.__class__.__name__, str(e)))
                continue


parsers.register("stocks3.parsers.Finam", FinamParser)
