"""FileReader module"""


class FileReader(object):
    """A simple file reader for data manipulation"""
    def __init__(self, fname, separator="\t", hasHeader=True):
        """
        :fname:
        :separator:
        :hasHeader:

        """
        super(FileReader, self).__init__()
        self.fname         = fname
        self.file          = open(self.fname, "r")
        self.header        = None
        self.hasHeader     = hasHeader
        self.columnNames   = []
        self.columnIndexes = {}
        self.columns       = {}
        self.data          = []
        self.separator     = separator

    def _skip_lines(self, count=0):
        for i in range(count):
            self.file.readline()

        if self.hasHeader:
            self.header = self.file.readline()

    def _handle_value(self, value):
        try:
            value = float(value)
        except ValueError:
            value = str(value).strip()
        return value

    def read_file(self, lines_to_skip=0):
        """Read the file after skipping a number of lines if necessary
        
        Parameters
        :lines_to_skip:
        """
        # Skip the first lines that are not header
        self._skip_lines(lines_to_skip)

        # Read the file then close it
        self.data = self.file.readlines()
        self.file.close()
        
        # Determine the names of the columns
        if self.hasHeader:
            self.columnNames = [ col.strip() for col in self.header.split(self.separator) ]
        else:
            self.columnNames = range(len(self.data[0].rstrip().split(self.separator)))
        self.columnIndexes = dict(zip(self.columnNames, range(len(self.columnNames))))

        # Populate the rows
        self.rows = []
        for line in self.data:
            row = []
            for elem in line.rstrip().split(self.separator):
                row.append(self._handle_value(elem))
            self.rows.append(row)
        
        # Populate the corresponding columns
        for name in self.columnNames:
            self.columns[name] = []
            for line in self.data:
                value = line.rstrip().split(self.separator)[self.columnIndexes[name]]
                self.columns[name].append(self._handle_value(value))
        
