import json

from django.core.management import BaseCommand

from api.models import Message
from gm_types.msg import MESSAGE_TYPE
from message.utils.es_abstract import get_esop, table_message


class Command(BaseCommand):

    def handle(self, *args, **options):
        messages = Message.objects.filter(body=None).all()
        for self in messages:
            body = None
            if self.type in [MESSAGE_TYPE.TEXT, MESSAGE_TYPE.AUDIO, MESSAGE_TYPE.IMAGE,
                             MESSAGE_TYPE.CUSTOMER_SRV_CTRL]:
                body = self.content
            elif self.type == MESSAGE_TYPE.SERVICE:
                body = int(self.content.lstrip('service:'))
            elif self.type == MESSAGE_TYPE.DOCTOR_TOPIC:
                body = int(self.content.lstrip('doctor_topic:'))
            elif self.type == MESSAGE_TYPE.DIARY:
                body = int(self.content.lstrip('diary:'))
            elif self.type == MESSAGE_TYPE.GIFT:
                channel, gift = self.content.split(',')
                channel_id = channel.split(':')[1]
                gift_id = gift.split(':')[1]
                body = {
                    'channel_id': int(channel_id),
                    'gift_id': int(gift_id)
                }
            elif self.type == MESSAGE_TYPE.TEXT_WITH_URL:
                query = {
                    "query": {
                        "match": {
                            "id": self.id
                        }
                    }
                }
                res = get_esop().search(
                    table_message,
                    body=query,
                    _source=['content']
                )
                # Not found, record it to count missing.
                if res['hits']['total'] != 1:
                    print('message id {} content is missing.'.format(self.id))
                else:
                    doc = res['hits']['hits'][0]
                    content = doc['_source']['content']
                    body = {
                        'text': content['text'],
                        'url': content['url']
                    }
            if body is not None:
                self.body = json.dumps(body, ensure_ascii=False)
                self.save(update_fields=['body'])
        print('Over')
