import time
from multiprocessing.dummy import Pool

from django.db import transaction
from django.core.management.base import BaseCommand

from intranet.femida.src.candidates.models import CandidateContact
from intranet.femida.src.utils.itertools import get_chunks


@transaction.atomic
def saver(_id):
    contact = CandidateContact.objects.select_for_update().get(id=_id)
    contact.save()


class Command(BaseCommand):

    help = 'Normalize contacts'

    def add_arguments(self, parser):
        parser.add_argument('--chunk-size', action='store', default=5000)
        parser.add_argument('--pool-size', action='store', default=12)

    def handle(self, *args, **options):
        pool_size = int(options['pool_size'])
        chunk_size = int(options['chunk_size'])

        contact_ids = list(
            CandidateContact.objects
            .filter(normalized_account_id='')
            .values_list('id', flat=True)
        )

        pool = Pool(pool_size)
        chunks = get_chunks(contact_ids, chunk_size)

        start = time.time()
        for i, chunk in enumerate(chunks, start=1):
            pool.map_async(saver, chunk).get()
            print('{} contacts was normalized in {} seconds'.format(
                i * chunk_size, time.time() - start
            ))
