import time
from datetime import datetime

from multiprocessing import Pool
from django.core.management import BaseCommand
from django.utils import timezone
from gm_types.gaia import USER_RIGHTS_LEVEL
from gm_types.user_hierarchy import EventType

from user_hierarchy.models import UserEventLog, UserGrowthValue
from .init_user_rights_base import path_base

STEP = 100


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


def process_bind_phone(lines):
    event_list = []
    value_list = []
    for line in lines:
        event_list.append(UserEventLog(user_id=line, event_type=EventType.BINDPHONE, value=20, trigger_time=timezone.now()))
        value_list.append(UserGrowthValue(user_id=line, value=20, level=USER_RIGHTS_LEVEL.V1))

    UserEventLog.objects.bulk_create(event_list)
    UserGrowthValue.objects.bulk_create(value_list)


class Command(BaseCommand):

    def handle(self, *args, **options):
        # bind phone
        print('------start-----')
        start_time = time.time()
        print(start_time)

        with open(path_base + 'has_phone_user_ids.txt', 'r') as f:
            lines = f.readlines()
            # lines = [next(f) for i in range(3333)]
            new_lines = chunk(lines, STEP)

            pool = Pool(processes=4)
            pool.map(process_bind_phone, new_lines)
            pool.close()
            pool.join()

        end_time = time.time()
        print(end_time)
        print('use {} s'.format(end_time - start_time))
        print('Done!')