# -*- coding: utf-8 -*-

import argparse
import common


def str2bool(v):
    return v.lower() in ('yes', 'true', '1')


def main():
    """ Main function with argument parsing """
    parser = argparse.ArgumentParser(description='Odoo database creation '
                                     'according to their names')
    parser = common.parser(parser)
    parser.add_argument('-a', '--action', type=str, default='create',
                        help='action for the database,' +
                        'default to create (others are drop, duplicate)')
    parser.add_argument('-d', '--database', type=str, required=True,
                        help='the targetted database')
    parser.add_argument('-dn', '--duplicate-name', type=str,
                        help=('name for duplicated database (optional : '
                              'name_copy otherwise'))
    parser.add_argument('-pw', '--password', type=str, required=True,
                        help='the odoo superadmin password')
    parser.add_argument('-dm', '--demo', type=str, default='False',
                        help='demonstration data')
    parser.add_argument('-l', '--lang', type=str, default='fr_FR',
                        help='default language')
    parser.add_argument('-dbpw', '--database_password', type=str, default='admin',
                        help='the database admin password, default to admin')

    args = parser.parse_args()
    # Connection
    odoo = common.connection(args)

    # Databases actions
    dblist = odoo.db.list()
    if args.action == 'create':
        if args.database in dblist:
            print 'database already exists'
        else:
            odoo.db.create(args.password, args.database, str2bool(args.demo),
                           args.lang, args.database_password)
    else:
        if args.database not in dblist:
            print 'database not found'
        elif args.action == 'drop':
            odoo.db.drop(args.password, args.database)
        elif args.action == 'duplicate':
            name = args.duplicate_name or args.database + '_copy'
            odoo.db.duplicate(args.password, args.database, name)

if __name__ == "__main__":
    main()
