from django.conf import settings
from django.core.management import BaseCommand

from message.utils.es import load_mapping
from message.utils.es_abstract import get_migrate_esop


class Command(BaseCommand):
    def handle(self, *args, **options):
        tables = filter(lambda d: d['name'] == "db3", settings.ES_MSG['database'])[0]['table']
        table_index_map = {
            table['name']: table['index']
            for table in tables
        }
        index = table_index_map['message']
        setting = {
            "settings": {
                "number_of_shards": 8,
                "number_of_replicas": 1
            },
            "mappings": load_mapping('message.v2')
        }
        esop = get_migrate_esop().client
        if esop.indices.exists(index):
            esop.indices.delete(index)
        esop.indices.create(index=index, body=setting)
        print('Index {} mappings and settings setup successfully'.format(index))

        index = table_index_map['conversation']
        setting['mappings'] = load_mapping('conversation.v2')
        if esop.indices.exists(index):
            esop.indices.delete(index)
        esop.indices.create(index=index, body=setting)
        print('Index {} mappings and settings setup successfully'.format(index))
