#!/usr/bin/env python

import sys
import os
from tornado.options import parse_command_line, parse_config_file
from tornado.options import options, print_help

import slickbird
from slickbird import orm
from slickbird import datparse


def main():
    defcfg = 'slickbird.cfg'
    parse_command_line()
    if options.config:
        parse_config_file(options.config)
    elif os.path.exists(defcfg):
        parse_config_file(defcfg)
    parse_command_line()  # override config file
    args = []
    for a in sys.argv[1:]:
        if a.startswith('--'):
            continue
        args.append(a)
    if len(args) != 3:
        print('Usage: {} <name> <directory> <dat>'.format(sys.argv[0]))
        print_help()
        sys.exit(1)
    dat = datparse.parse(filename=args[2])
    session = orm.make_session(options.database)()
    cadder = slickbird.CollectionAdder(
        session=session,
        home=options.home,
        name=args[0], directory=args[1], filename=args[2], dat=dat)
    for gn, gd in dat['games'].items():
        cadder.game_add(gn, gd)
    cadder.done()


if __name__ == "__main__":
    main()
