import os
import xlrd
from ExceptionHelper import FileNotExistError

class XlsModerator(object):
    """
    Helper class for excel data operations on excel spread sheet
    """

    _data = {}
    _path = None
    
    def __init__(self, path, isFirstRowHeader=True):
        """
        Constructor for class 

        @param path : path to the excel file
        @param isFirstRowHeader : is the first row of the excel file a header row?
                If true, the return result for reach row will be dictionary, otherwise, it will be a list
                
        """
        if not os.access(path, os.F_OK):
            raise FileNotExistError('Cannot find the xls file [%s]' % path)
        self._path = path
        self.xls2dict(isFirstRowHeader=isFirstRowHeader)
        
    def xls2dict(self, sheet=None, isFirstRowHeader=True):
        """
        Convert excel data to dictionary (key for sheet name), the result will be stored in data attribute

        @param sheet: name of the specific sheet to fetch the data
        @param isFirstRowHeader : is the first row of the excel file a header row?
                If true, the return result for reach row will be dictionary, otherwise, it will be a list
        """
        with xlrd.open_workbook(self._path) as wb:
            for s in range(wb.nsheets):
                worksheet = wb.sheet_by_index(s)
                if not sheet or worksheet.name in sheet:
                    num_rows, curr_row = worksheet.nrows, 0
                    self._data[worksheet.name] = []
                    if isFirstRowHeader:
                        keyValues = [x.value for x in worksheet.row(0)]
                        curr_row = 1
                    while curr_row < num_rows:
                        if isFirstRowHeader:
                            row = dict()
                            for idx, val in enumerate(worksheet.row(curr_row)):
                                if row.has_key(keyValues[idx]):
                                    if not isinstance(row[keyValues[idx]], list):
                                        row[keyValues[idx]] = [row[keyValues[idx]]]
                                    row[keyValues[idx]].append(unicode(val.value).encode('utf-8').strip())
                                else:
                                    row[keyValues[idx]] = unicode(val.value).encode('utf-8').strip()
                        else:
                            row = list()
                            for val in worksheet.row(curr_row):
                                row.append(unicode(val.value).encode('utf-8').strip())
                        curr_row += 1
                        self._data[worksheet.name].append(row)

    @property
    def data(self):
        """
        The excel data extracted from the file
        """
        return self._data
        
    def get_sheet_data(self, sheet):
        """
        Get the excel sheet data on specific sheet
        
        @param sheet: name of the sheet to fetch the data
            
        @return: a list of data from the specified sheet or empty list if no sheet found
        """
        return self._data.get(sheet) or []
