# -*- coding: utf-8 -*-
"""
Парсер для imf.org.
"""
from stocks3.core.parser import Parser
from stocks3.core.factories import parsers
from datetime import datetime
import csv


class ImfParser(Parser):
    def parse(self, place):
        f = place.read()
        reader = csv.reader(f.split('\n'), delimiter="\t")
        source_date = ''
        for row in reader:
            if len(row) == 1:
                try:
                    # Пробуем распарсить строку в дату - если получилось, записываем это в source_date
                    datetime.strptime(row[0], "%d-%b-%y")
                    source_date = row[0]
                except ValueError as e:
                    pass
                finally:
                    pass
            if len(row) != 3:
                continue
            try:
                quote_name = row[0].lower()
                value = float(row[2].replace(',', ''))
                price = self.default_map.make_price_date(quote_name, source_date, value)
                if price is not None:
                    yield price
            except ValueError as e:
                pass


parsers.register("stocks3.parsers.imf", ImfParser)
