import xlsxwriter
import csv
import sys

# This is going to store the workbooks in an easy to access dictionary
worksheets = {}

# Create a workbook.
workbook = xlsxwriter.Workbook('output.xlsx')

# This method writes the data row to the worksheet
def write_row(values, src, type):
    col = 0
    row = worksheets[src]['current_row']

    for value in values:
        worksheets[src]['sheet'].write(row, col, value)

        if len(value) > 0 and type == 'row':
            worksheets[src]['column_data_frequency'][col] = "data"

        col += 1

    worksheets[src]['current_row'] += 1

# This initializes the counter that checks if a colum has data to zero
def init_column_data_frequency(row):
    src_name = row['src']
    for i in range(0, len(row.keys())):
        worksheets[src_name]['column_data_frequency'][i] = "no_data"
    
# This method adds a new worksheet to the workbook
def add_worksheet(row):
    src_name = row['src']

    if not workbook.get_worksheet_by_name(src_name[0:30]):
        worksheet = workbook.add_worksheet(src_name[0:30])

        worksheets[src_name] = {}
        worksheets[src_name]['sheet'] = worksheet
        worksheets[src_name]['current_row'] = 0
        worksheets[src_name]['column_data_frequency'] = {}

        init_column_data_frequency(row)
        write_row(row.keys(), src_name, 'header')


# This method adds the row of data from the csv to the appropriate worksheet
# based on categorization by common scr value
def add_row_to_worksheet(row):
    if row['src'] != '':
        add_worksheet(row)
        write_row(row.values(), row['src'], 'row')

# This creates a dictionary of the row info read from the csv
def create_dict(row):
    row_data = {}
    keys_str = row.keys()[0]
    value_str = row[keys_str]
    keys = keys_str.split(';')
    values = value_str.split(';')

    for i in range(0, len(keys)):
        key = keys[i]
        row_data[key] = values[i]

    return row_data

# This method hides columns that has no data
def hide_empty_columns():
    for key in worksheets.keys():
        column_data_keys = worksheets[key]['column_data_frequency'].keys()
        sheet = worksheets[key]['sheet']
        for index in column_data_keys:
            if worksheets[key]['column_data_frequency'][index] == "no_data":
                print index
                sheet.set_column(index, index, None, None, {'hidden': True})
                    
            else:
                print "has data"

# This processes the csv file passed in by the user as commandline argument
def process_csv(file_name):
    # This reads the csv file into the app
    with open(file_name) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            row_dict = create_dict(row)
            add_row_to_worksheet(row_dict)

        hide_empty_columns()
        workbook.close()


#This is the entry point of this script
def main():
    arg_list = sys.argv
    try:
        filename = arg_list[1]
        process_csv(filename)
        
    except ValueError:
        print ValueError
        workbook.close()

# starts the app.
main()
