import argparse
import logging
import os
import sys
import time
from multiprocessing import Pool
from hongbao_manager import HongbaoManager
from my_util import init_logger
from argparse import RawTextHelpFormatter


def parse_args():
    """parse args for mysql transaction commitor"""

    parser = argparse.ArgumentParser(description='''
    Hongbao transaction commitor.
    
    use examples:
    # create users
    python hongbao_commitor.py -m user -u 200 -f 20 -g 10 --members 50
    
    # create hongbao
    python hongbao_commitor.py -m hongbao  -c 1 -u 100 -b 50
    
    # drop database
    python hongbao_commitor.py -e cleanup
    ''', formatter_class=RawTextHelpFormatter, add_help=False)

    parser.add_argument("-m", "--method", type=str, dest='method',
                        help='The methods of: user,hongbao')
    parser.add_argument("-c", "--threads", type=int, default=1, dest='threads',
                        help='How many threads will be running.')
    parser.add_argument("-s", "--sleep", type=int, default=0, dest='sleep',
                        help='Sleep seconds between each transaction. ')
    parser.add_argument('-u', '--users', dest='users', type=int,
                        help='How many users will be created.', default=1000)
    parser.add_argument('-f', '--friends', dest='friends', type=int,
                        help='How many friends each user will be created.', default=50)
    parser.add_argument('-g', '--groups', dest='groups', type=int,
                        help='How many groups each user will be created.', default=5)
    parser.add_argument('--members', dest='members', type=int,
                        help='How many members each group will be created.', default=100)
    parser.add_argument('-b', '--hongbaos', dest='hongbaos', type=int,
                        help='How many friends each user will be created.', default=5)
    parser.add_argument("-l", '--level', type=int, dest='log_level', default=logging.INFO,
                        help='logging level: CRITICAL = 50, ERROR = 40, WARNING = 30, INFO = 20, DEBUG = 10')
    parser.add_argument('-h', '--help', dest='help', action='store_true', help='help information', default=False)

    return parser


def command_line_args(args):
    need_print_help = False if args else True
    parser = parse_args()
    args = parser.parse_args(args)
    if args.help or need_print_help:
        parser.print_help()
        sys.exit(1)
    if not args.method:
        raise ValueError('The method must be specified and not empty.')
    return args


def create_users_task(name, level, users=5, friends=20, groups=2, groups_members=30, sleep=0):
    start = time.time()
    log_name = os.path.basename(__file__).replace(".py", "") + "_" + str(name)
    logger = init_logger(log_name=log_name, level=level)
    logger.debug('Run task %s (%s)...' % (name, os.getpid()))
    pm = HongbaoManager(logger=logger)
    pm.create_users(users=users, friends=friends, groups=groups, groups_members=groups_members, sleep=sleep)
    end = time.time()
    logger.debug('Task %s runs %0.2f seconds.' % (name, (end - start)))


def create_hongbaos(name, level, users=100, hongbaos=5, sleep=0):
    start = time.time()
    log_name = os.path.basename(__file__).replace(".py", "") + "_" + str(name)
    logger = init_logger(log_name=log_name, level=level)
    logger.debug('Run task %s (%s)...' % (name, os.getpid()))
    pm = HongbaoManager(logger=logger)
    pm.create_hongbaos(users=users, hongbaos=hongbaos, sleep=sleep)
    end = time.time()
    logger.debug('Task %s runs %0.2f seconds.' % (name, (end - start)))


if __name__ == '__main__':
    args = command_line_args(sys.argv[1:])
    method = args.method
    max_threads = args.threads
    log_level = args.log_level

    p = Pool(max_threads)
    for i in range(max_threads):
        if method == "user":
            p.apply_async(create_users_task, args=(i, log_level, args.users, args.friends, args.groups, args.members, args.sleep))
        elif method == "hongbao":
            p.apply_async(create_hongbaos, args=(i, log_level, args.users, args.hongbaos, args.sleep))
    p.close()
    p.join()
    print('All done.')
