'''
helper module which provides unicode related stuff.
'''

import csv


class UnicodeCsvReader(object):
    """
    unicode aware csv.CsvReader.
    thanks to http://stackoverflow.com/a/6187936/201743
    """
    def __init__(self, f, encoding="utf-8", **kwargs):
        self.csv_reader = csv.reader(f, **kwargs)
        self.encoding = encoding

    def __iter__(self):
        return self

    def next(self):
        # read and split the csv row into fields
        row = self.csv_reader.next()
        # now decode
        return [unicode(cell, self.encoding) for cell in row]

    @property
    def line_num(self):
        return self.csv_reader.line_num


class UnicodeDictReader(csv.DictReader):
    """
    unicode aware csv.DictReader.
    thanks to http://stackoverflow.com/a/6187936/201743
    """
    def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds):
        csv.DictReader.__init__(self, f, fieldnames=fieldnames,
                                restkey=u'rest', **kwds)
        self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds)
