#!/usr/bin/env python3

from __future__ import print_function
import argparse
import os
import sys
from pprint import pprint


try:
    import boxes
except ImportError:
    sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/..")
    import boxes

import boxes.generators

def printusage():
    print("""Usage:
boxes [NAME] [options]
  --list	list possible names
  --help	show help for given NAME
""")

def main():
    generators = {name.split('.')[-1].lower() : box for name, box in
                  boxes.generators.getAllBoxGenerators().items()}
    groups = boxes.generators.ui_groups
    groups_by_name = boxes.generators.ui_groups_by_name
    for name, box in generators.items():
        groups_by_name.get(box.ui_group,
                           groups_by_name["Misc"]).add(box)
    if len(sys.argv) > 1 and sys.argv[1].startswith("--id="):
        del sys.argv[1]
    if len(sys.argv) == 1:
        printusage()
    elif sys.argv[1] == '--list':
        print("Available generators:")
        for group in groups:
            print('\n' + group.title)
            if group.description:
                print('\n%s\n' % group.description)
            else:
                print()
            for box in group.generators:
                print(" * ", box.__name__, ' - ',  box.__doc__ or '')
    else:
        name = sys.argv[1].lower()
        if name.startswith("--generator="):
            name = name[12:]
        if (name in generators):
            box = generators[name]()
            box.parseArgs(sys.argv[2:])
            box.render()
        else:
            sys.stderr.write(str(sys.argv))
            sys.stderr.write("Unknown generator name. Use boxes --list to get a list of available commands.")

main()
