#!/usr/bin/env python
import argparse
import json
import os
def table_from_dict(data):
    headers = ['subdir',
                'name',
                'version',
                'build',
                'build_number',
                'license',
                'depends',
                'md5',
                'sig',
                'size']
    html = '
'
    for header in headers:
        html += '| ' + header.upper() + ''
    for pkg_name, pkg_info in sorted(data.items()):
        html += ' | '
        html += '
'
        for header in headers:
            if header not in pkg_info.keys():
                pkg_info[header] = '-'
            for key, value in pkg_info.items():
                if value is None or not value:
                    value = '-'
                if key == header:
                    if isinstance(value, list):
                        html += '| '
                        for record in sorted(value):
                            html += '' + record + ''
                        html += ''
                    else:
                        html += ' | ' + str(value) + ''
        html += ' | 
'
    html += ''
    html += '
'
    return html
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('repodata', action='store')
    args = parser.parse_args()
    filename = args.repodata
    if '.json' not in os.path.splitext(filename)[1]:
        print("JSON formatted file required.")
        exit(1)
    repodata = None
    with open(filename, 'r') as data:
        repodata = json.load(data)
    if repodata is None:
        print("Invalid JSON file.")
        exit(1)
    print('')
    print('')
    print('Repository Contents')
    print('')
    print('')
    print('')
    #for key, subdict in sorted(repodata['packages'].items()):
    #    print("{0:50s} {1:>40s} {2:>20d}kb".format(key, subdict['md5'], subdict['size']))
    print(table_from_dict(repodata['packages']))
    print('')
    print('')