# 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 Message
import datetime
from message.utils.es_abstract import table_message
from message.utils.es_abstract import get_esop
from message.utils.es import tzlc
from api.models.types import MESSAGE_TYPE


def get_messages(year, month):
    assert isinstance(year, int)
    messages = Message.objects.filter(send_time__year=year, send_time__month=month).order_by('id')
    return messages


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 = get_messages(year, month).count()
        print('---count:{}---'.format(count))
        thread_nums = cpu_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()
            print('---Thread_at:{}:{}:{}---'.format(i, start, end))
        for t in threads:
            t.join()
        print('----DONE----')

    def update(self, start, end, year, month):
        messages = get_messages(year, month)[start: end].iterator()
        for message in messages:
            msg_es = {
                'id': message.id,
                'send_user': {
                    'id': message.user_id,
                },
                'send_time': tzlc(message.send_time),
                'type': message.type,
                'content': {},
                'conversation_id': message.conversation_id
            }

            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
                }
            self.esop.index(
                table=table_message,
                id=message.id,
                body=msg_es
            )
            print(message.id)
