# coding: utf-8
import math
from multiprocessing import cpu_count
from threading import Thread

from django.core.management import BaseCommand

from api.models import MarkUser, Conversation


class Command(BaseCommand):

    def handle(self, *args, **options):
        count = MarkUser.objects.count()
        thread_nums = cpu_count()

        step = int(math.ceil((float(count) / thread_nums)))
        threads = []
        for i, left in enumerate(range(0, count, step)):
            right = min(count, left + step)
            t = Thread(target=self.migrate, args=(left, right), name=i + 1)
            threads.append(t)
            t.start()

        for t in threads:
            t.join()

    def migrate(self, left, right):
        mus = MarkUser.objects.all()[left: right]
        for mu in mus:
            uid_hash = Conversation.gen_uid_hash([mu.user_id, mu.target_user_id])
            c = Conversation.objects.filter(uid_hash=uid_hash).first()
            if not c:
                continue
            cus = c.user_status_set.filter(user_id=mu.user_id).first()
            if not cus:
                continue
            cus.comment = mu.comment
            cus.save(update_fields=['comment'])
