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

from django.core.management import BaseCommand

from api.models.message import Conversation, ConversationUserStatus
from message.utils.conversation import get_conversation_head_bulk_action
from message.utils.es_abstract import get_esop
from message.utils.es import tzlc
from api.models.types import MESSAGE_TYPE


class Command(BaseCommand):

    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        self.esop = get_esop()
    def add_arguments(self, parser):
        parser.add_argument('-y', help="sync year; default 2019", type=int, default=2019)
        parser.add_argument('-m', help="sync month; default 1", type=int, default=1)

    def handle(self, *args, **options):
        if options['y']:
            year = options['y']
        else:
            year = 2019
        if options['m']:
            month = options['m']
        else:
            month = 1
        print('----start----')
        count = Conversation.objects.filter(last_reply_time__year=year, last_reply_time__month=month).count()
        thread_nums = cpu_count()
        print('---count:{}---'.format(count))
        print('---Thread:{}---'.format(thread_nums))
        step = int(math.ceil((float(count) / thread_nums)))
        threads = []
        for i, start in enumerate(range(0, count, step)):
            end = min(count, start + step)
            t = Thread(target=self.update, args=(start, end, year, month), name=i + 1)
            threads.append(t)
            t.start()

        for t in threads:
            t.join()
        print('---DONE---')

    def update(self, start, end, year, month):

        def get_user_last_name(user_status):
            from api.models.user import User
            try:
                return User.objects.get(id=user_status.user_id).last_name
            except:
                return ''

        def format_message(message):
            msg_es = {
                        'id': message.id,
                        'send_user': {
                            'id': message.user_id,
                        },
                        'send_time': tzlc(message.send_time),
                        'type': message.type,
                        'content': {}
                    }

            if message.type:
                if message.type == MESSAGE_TYPE.TEXT:
                    msg_es['content'] = {
                        'text': message.content
                    }
                elif message.type == MESSAGE_TYPE.AUDIO:
                    msg_es['content'] = {
                        'audio': message.content
                    }
                elif message.type == MESSAGE_TYPE.IMAGE:
                    msg_es['content'] = {
                        'image': message.content
                    }
                elif message.type == MESSAGE_TYPE.SERVICE:
                    msg_es['content'] = {
                        'service_id': message.body
                    }
                elif message.type ==  MESSAGE_TYPE.DIARY:
                    msg_es['content']= {
                        'diary_id': message.body
                    }
                elif message.type == MESSAGE_TYPE.GIFT:
                    msg_es['content'] = json.loads(message.body)
                else:
                    msg_es['content'] = {
                        'text': message.content
                    }
            else:
                msg_es['type'] = MESSAGE_TYPE.TEXT
                msg_es['content'] = {
                    'text': message.content
                }
            return msg_es

        convs_body = {}
        conversations = Conversation.objects.filter(last_reply_time__year=year, last_reply_time__month=month)[start: end]
        for conversation in conversations.iterator():
            convs_body[conversation.id] = {
                'id': conversation.id,
                'last_reply_time': tzlc(conversation.last_reply_time),
                'is_star_by_doctor': conversation.user_status_set.filter(is_star=True).exists(),
                'conversation_type': conversation.conversation_type,
                'users': [{
                            'id': user_status.user_id,
                            'last_name': get_user_last_name(user_status),
                            'is_unread': user_status.read_status
                        } for user_status in conversation.user_status_set.all()],
                'messages': [format_message(message) for message in conversation.message_set.all().iterator()]
            }
            print(conversation.id)
        convs_body = convs_body.values()
        actions = map(get_conversation_head_bulk_action, convs_body)
        print self.esop.helper_bulk(actions)
