
from multiprocessing.pool import ThreadPool

from django.core.management import BaseCommand

from api.models import User, DeviceBinding
from statistic.models import Device


def create_device_binding(user):
    """
    create device binding.
    :param user:
    :return:
    """
    device = Device.objects.filter(user=user).order_by('-created_time').first()
    city = user.userextra.city

    province = city.province if city else None
    DeviceBinding.objects.update_or_create(user=user, defaults={
        'device': device.device_id, 'city': city, 'province': province
    })
    print("[UserBinding]: %s Complete." % user.id)


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('-o', '--offset', type=int, help="offset user_id.")
        parser.add_argument('-l', '--limit', type=int, help="create device binding limit.")

    def handle(self, *args, **options):
        offset = options['offset']
        limit = options['limit'] or 1000

        queryset = User.objects.order_by('id')
        if offset:
            queryset = queryset.filter(id__gt=offset)

        pool = ThreadPool(processes=500)
        pool.map(create_device_binding, queryset[:limit])
