#!/usr/bin/env python
"""csv-render [<options>] <file.csv>

Render a CSV file to various output formats.
"""
__version__ = "Revision: 1.1 "
__author__ = "Martin Blais <blais@furius.ca>"


import re


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip(), version=__version__)

    parser.add_option('-f', '--format', action='store', type='choice',
                      metavar='OUTPUT', choices=['align', 'table'],
                      default='align',
                      help="Specify output format for CSV file.")

    parser.add_option('-r', '--right-numbers', action='store_true',
                      help="Align floating-point numbers to the right.")

    opts, args = parser.parse_args()

    if len(args) != 1:
        raise parser.error('You must specify a single csv file to render.')

    import csv
    reader = csv.reader(file(args[0]))
    rows = []
    maxcol = 0
    for row in reader:
        rows.append(row)
        maxcol = max(maxcol, len(row))
    maxrow = len(rows)
    
    # calculate max width for each column
    width = []
    for col in xrange(maxcol):
        m = 0
        for row in xrange(maxrow):
            r = rows[row]
            if col < len(r):
                mr = len(r[col])
                m = max(m, mr)
        width.append(m)
        
    sre = re.compile('^\d+\.\d+$')

    # pre-align rows for text output
    arows = []
    for row in xrange(maxrow):
        out = []
        r = rows[row]
        for col in xrange(maxcol):
            if col < len(r):
                s = r[col]
                if opts.right_numbers and sre.match(s):
                    fmt = '%%%ds'
                else:
                    fmt = '%%-%ds'
                out.append( (fmt % width[col]) % r[col] )
            else:
                out.append(' ' * width[col])
        arows.append(out)

    if opts.format == 'align':
        padding = '  '
        for arow in arows:
            print padding.join(arow)
    elif opts.format == 'table':
        o = []
        for ncol in width:
            o.append('-' * (ncol + 2))
        sline = '+' + '+'.join(o) + '+'

        padding = ' | '
        for arow in arows:
            print sline
            print '| ' + padding.join(arow) + ' |'
        print sline
        
    else:
        assert False
    
if __name__ == '__main__':
    main()
