# -*- coding: UTF-8 -*-
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from search.utils.es import get_es
from trans2es.utils.es import put_mapping, load_mapping, create_index, init_alias


class Command(BaseCommand):
    help = 'push mapping to elasticsearch'

    def handle(self, *args, **options):
        es = get_es()

        type_mapping = {
            'topic': 'problem',
            'tag': 'tag',
            'itemwiki': 'itemwiki',
            'diary': 'diary',
            'service': 'service',
            'doctor': 'doctor',
            'user': 'user',
            'question': 'question',
        }

        index_prefix = settings.ES_INDEX_PREFIX

        for doc_type in type_mapping.values():
            self.work(es=es, index_prefix=index_prefix, doc_type=doc_type,
                      delete=False)

    def work(self, es, index_prefix, doc_type, delete=False):
        create_index(es=es, index_prefix=index_prefix, doc_type=doc_type)

        init_alias(es=es, index_prefix=index_prefix, doc_type=doc_type)

        m = load_mapping(doc_type=doc_type)
        print(put_mapping(es=es, index_prefix=index_prefix, doc_type=doc_type,
                          mapping=m, delete=delete))
