#!/usr/bin/python

import csv
import xlwt
import sys
import os.path
import time

from os import makedirs
from subprocess import call
from tempfile import mkdtemp

import argparse

parser = argparse.ArgumentParser(description='Write excel spreadsheet from a tab seperated input on stdin.')
parser.add_argument('infile', help='Input file (use - for stdin)')
parser.add_argument('outfile', help='File to output to (default data.xls)', default='data.xls')
parser.add_argument('--delim', default='##worksheet sheet#',
                   help='Delimiter between worksheets (default ##worksheet sheet#)')
parser.add_argument('--email', default=False, action='store_true', help='Attach the excel file to an email')

args = parser.parse_args()

wb = xlwt.Workbook(encoding='utf-8')
ws = None
sheet_count = 1
sheet_row = -1
class ReadlineIterator(object):
    """An iterator that calls readline() to get its next value."""
    def __init__(self, f): self.f = f
    def __iter__(self): return self
    def next(self):
    	global ws
    	global wb
    	global sheet_count
    	global sheet_row
        line = self.f.readline()
        if line.find(args.delim) >= 0:
        	other_delim = line.replace(args.delim,"").rstrip()
        	if len(other_delim) == 0:
        		other_delim = "Sheet %s" % sheet_count
        	ws = wb.add_sheet(other_delim)
        	sheet_count = sheet_count + 1
        	sheet_row = -1
	       	return next(self)
        if ws is None:
        	ws = wb.add_sheet("Sheet %s" % sheet_count)
        	sheet_count = sheet_count + 1
        sheet_row = sheet_row + 1
        if line: return line
        else: raise StopIteration


infile = sys.stdin

if args.infile == '-':
	pass
else:
	infile = open(args.infile, 'r')


# Create a TSV file reader.
tsv_reader = csv.reader(ReadlineIterator(infile), delimiter='\t')

# Read the row data from the TSV file and write it to the XLSX file.
row_num = 0
col_num = 0
for row, rowdata in enumerate(tsv_reader):
	for col,data in enumerate(rowdata):
	    ws.write(sheet_row, col, data)

if args.email:
	temp_dir = mkdtemp()
	if len(temp_dir) > 1 :
		wb.save(os.path.join(temp_dir,args.outfile))
        call(["open", "-a" , "/Applications/Microsoft Office 2011/Microsoft Outlook.app", os.path.join(temp_dir,args.outfile)])
	time.sleep(20)
else:
#    directory = os.path.dirname(args.outfile)
#    if len(directory) > 0 and not os.path.exists(directory):
#        os.makedirs(directory)
	wb.save(args.outfile)
