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

import argparse
import common


def main():
    """ Main function with argument parsing """
    parser = argparse.ArgumentParser(description='Manage Odoo modules '
                                     'according to their names')
    parser = common.parser(parser)
    parser.add_argument('-db', '--database', type=str, required=True,
                        help='the targetted database')
    parser.add_argument('-dbu', '--database-user', type=str, default='admin',
                        help='the odoo database admin username')
    parser.add_argument('-dbpw', '--database-password', type=str,
                        required=True,
                        help='the odoo database admin password')
    parser.add_argument('-a', '--action', type=str, required=True,
                        choices=['listupdate', 'install', 'update', 'remove'],
                        help='the action asked : listupdate, install, update '
                        'or remove')
    parser.add_argument('-n', '--names', type=str, default='base',
                        help='module names coma separated')
    args = parser.parse_args()
    if args.names:
        args.names = args.names.split(',')

    # Connection
    odoo = common.connection(args)
    odoo.login(args.database, args.database_user, args.database_password)

    # Modules actions
    Module = odoo.env['ir.module.module']
    if args.action == 'listupdate':
        Module.update_list()
    else:
        if len(args.names) > 0:
            mids = Module.search([('name', 'in', args.names)])
            if args.action == 'install':
                Module.button_immediate_install(mids)
            elif args.action == 'update':
                Module.button_immediate_upgrade(mids)
            else:
                Module.button_immediate_uninstall(mids)


if __name__ == "__main__":
    main()
