import csv
import os
import types

decimals = 1

def getKeys(dicts):
    for dict in dicts:
        keys = set()
        for key in dict.keys():
            keys.add(key)
    keys = list(keys)
    keys.sort()
    keyDict = {}
    for key in keys:
        keyDict[key] = key
    return (keys, keyDict)

def addToCSV(dict, filename, fieldnames=None):
    rows = []
    writeTitles = True
    if os.path.exists(filename):
        rows = readCSV(filename, fieldnames)
        if len(rows) > 0:
            writeTitles = False
    if not isinstance(dict, list):
        dict = [dict] 
    writeCSV(rows+dict, filename, fieldnames, writeTitles)

def selectRowsCSV(rows, conditions, invert=False):
    selected = []
    for row in rows:
        for key in conditions.keys():
            exists = row.has_key(key) and row[key] == conditions[key]
            if invert: exists = not exists
            if exists:
                selected.append(row)
    return selected

def getValueSet(rows, column):
    values = set()
    for row in rows:
        if row.has_key(column):
            values.add(row[column])
    return values

def remapKeys(rows, dict):
    newRows = []
    for row in rows:
        newRow = {}
        for k in row.keys():
            value = row[k]
            key = k
            if key in dict.keys():
                key = dict[key]
            newRow[key] = value
        newRows.append(newRow)
    return newRows

def removeKeys(rows, keys):
    newRows = []
    for row in rows:
        newRow = {}
        for k in row.keys():
            value = row[k]
            key = k
            if key not in keys:
                newRow[key] = value
        newRows.append(newRow)
    return newRows

def writeCSV(dict, filename, fieldnames=None, writeTitles=True):
    if not isinstance(dict, list):
        dict = [dict]
    if fieldnames == None:
        keys, keyDict = getKeys(dict)
    else:
        keys = fieldnames
        keyDict = {}
        for key in fieldnames:
            keyDict[key] = key
    csvFile = open(filename, "wb")
    writer = csv.DictWriter(csvFile, fieldnames=keys)
    if writeTitles:
        writer.writerow(keyDict)
    for row in dict:
        writer.writerow(row)
    csvFile.close()

def readCSV(filename, fieldnames=None):
    csvFile = open(filename, "rb")
    reader = csv.DictReader(csvFile, fieldnames=fieldnames)
    rows = []
    while True:
        try:
            row = reader.next()
            rows.append(row)
        except StopIteration:
            break
    csvFile.close()
    return rows

def interpret(data):
    try:
       floatValue = float(data)
       try:
           intValue = int(data)
           if floatValue != float(intValue):
               return floatValue
           else:
               return intValue
       except:
           return floatValue
    except:
       return data
    
def floatToString(data):
    if isinstance(data,float):
        return ("%."+str(decimals)+"f") % data
    else:
        return data

def getLatexString(data):
    data = interpret(data)
    data = floatToString(data)
    string = str(data)
    string = string.replace("_","\\_")
    return string

def layoutLatex(row, key):
    return getLatexString(row[key])

def writeLatex(dict, filename, keys = None, empty=" ", layout=None, extraHeaderLines=None):
    if layout == None:
        layout = layoutLatex
    
    if not isinstance(dict, list):
        dict = [dict]
    if keys == None:
        keys = getKeys(dict)[0]
    
    file = open(filename, "wt")
    file.write("% This file is generated by JariSandbox/ComplexPPI/Source/Utils/TableUtils.py\n")
    file.write("% DO NOT edit manually, as your changes WILL BE OVERWRITTEN!\n")
    
    file.write("\\begin{tabular}{ | c | ")
    for key in keys:
        file.write(" c |")
    file.write( "}\n")
    file.write("\\hline\n")
    
    # extra header
    if extraHeaderLines != None:
        for line in extraHeaderLines:
            file.write(line+"\n")
    
    # Header                      
    isFirst = True
    keyDict = {}
    for key in keys:
        keyDict[key] = key
    for key in keys:
        if isFirst:
            file.write(layout(keyDict, key))
            isFirst = False
        else:
            file.write(" & " + layout(keyDict, key))
    file.write(" \\\\\n")
    file.write("\\hline\n")                     
    for row in dict:
        isFirst = True
        if type(row) == types.StringType:
            file.write(row)
        else:
            for key in keys:
                if not isFirst:
                    file.write(" & ")
                else:
                    isFirst = False
                if row.has_key(key):
                    file.write(layout(row, key))
                else:
                    file.write(empty)
            file.write(" \\\\\n")
    #file.write("1 & 2 & 3 \\\\\n")
    #file.write("4 & 5 & 6 \\\\\n")
    #file.write("7 & 8 & 9 \\\\\n")
    file.write("\\hline\n")
    file.write("\\end{tabular}\n")
    file.close()
    