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

"""
Этот парсер, в основном, используется для тестов. Он забирает данные из
csv-файла (по формату похожего на mordareg_export.csv).
"""

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


import csv
from stocks3.core.parser import Parser
from stocks3.core.place import FilePlace
from stocks3.core.factories import parsers


class CsvParser(Parser):
    places = [FilePlace]

    def _parse_csv_row(self, row):
        assert len(row) == 5, "Invalid row: %s" % ";".join(row)
        return row

    def parse(self, place):
        f = place.open_for_read()
        try:
            reader = csv.reader(f, delimiter=";")
            for row in reader:
                region, sourceQuoteId, sourceDatetime, buy_value, sell_value = \
                    self._parse_csv_row(row)
                region = int(region)
                buy_value = float(buy_value)
                if sell_value != "":
                    sell_value = float(sell_value)
                    price = self.default_map.make_dual_price_date(sourceQuoteId, sourceDatetime, buy_value, sell_value)
                else:
                    price = self.default_map.make_price_date(sourceQuoteId, sourceDatetime, buy_value)
                if price is not None:
                    price.onlyForRegion(region)
                    yield price
        finally:
            f.close()


parsers.register("stocks3.parsers.Csv", CsvParser)


