from multiprocessing import Pool

from django.core.management import BaseCommand
from gm_types.gaia import USER_RIGHTS_LEVEL

from utils.rpc import get_rpc_invoker

from user_hierarchy.models import UserGrowthValue
from utils.rpc import logging_exception


STEP = 100


def chunk(arr, step):
    return [arr[i: i+step] for i in range(0, len(arr), step)]


def update_user_level_list(users_list):
    try:
        r = get_rpc_invoker()
        r['api/user/update_level_list'](users_list=users_list).unwrap()
    except Exception as e:
        logging_exception()

    return


class Command(BaseCommand):
    def handle(self, *args, **options):
        users = UserGrowthValue.objects.exclude(level=USER_RIGHTS_LEVEL.V1).values('user_id', 'level')
        users_list = chunk(list(users), STEP)

        pool = Pool(processes=4)
        pool.map(update_user_level_list, users_list)
        pool.close()
        pool.join()
