#!/usr/bin/env python3
import lee
import argparse

KEYS = ['name', 'type', 'index', 'primary', 'unique', 'auto_increment',
    'null', 'unsigned', 'length', 'default']

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output', help='the output file')
    parser.add_argument('--table', help='the table name')
    parser.add_argument('path', help='sqlite://path/to/the/sqlite\nmysql://host:port?user=dbuser&passwd=dbpasswd&db=dbname')
    args = parser.parse_args()
    return args

template = '''
class _{class_name}(Model):
    columns = [
        {columns}
    ]
    table_name = '{table_name}'
    __slots__ = []

{class_name} = Table(_{class_name})
'''

def format_column(column):
    output = []
    for key in KEYS:
        val = column.get(key)
        if val:
            if isinstance(val, str):
                val = "'%s'"%val
            else:
                val = str(val)
            output.append("'{}': {}".format(key, val))

    return "{%s}"%', '.join(output)

def main():
    args = parse_args()
    lee.connect(args.path)
    if args.table:
        tables = [args.table]
    else:
        tables = lee.show_tables()

    output = []
    output.append('from lee import Table, Model')

    for table in tables:
        columns = lee.desc_table(table)
        columns = [format_column(column) for column in columns]
        columns = ',\n        '.join(columns)
        output.append(template.format(table_name=table,
            class_name=table.capitalize(),
            columns=columns))

    if args.output:
        with open(args.output, 'w') as f:
            f.write('\n'.join(output))
    else:
        print('\n'.join(output))

if __name__ == '__main__':
    main()
