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


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

    from optparse import make_option
    option_list = BaseCommand.option_list + (
        make_option('-t', '--type', dest='type', help='type name to dump data to elasticsearch', metavar='TYPE'),
        make_option('-d', '--delete', dest='delete', action='store_true', default=False,
                    help='whether to delete original mapping with its data'),
        make_option('-i', '--index-prefix', dest='index_prefix', help='specify index name', metavar='INDEX_PREFIX'),
        make_option('-n', '--index_version', dest='index_version', help='specify index version,like v1', default=''),
    )

    def handle(self, *args, **options):
        if not options['type']:
            raise CommandError('type name must be specified')
        elif not (options['type'] in [
            'topic',  # 帖子
            'tag',  # 圈子
            'itemwiki',  # 百科
            'diary',  # 日记本
            'service',  # 福利
            'doctor',  # 医生
            'user',  # 用户
            'question',  # 问答
            'board',  # 排行榜
            'answer',  # 回答
            'article',  # 专栏
            'sku',  # sku
            '_all',  # 全部
            'diary_norms_disable',
            'service_norms_disable',
            'newwiki',
            'wiki_keyword',
            'qa_top',
            "tractate",
            "doctortractate",
            "service_ngram",
            "principal",
            "subscript_article",
            "user_album"
        ]):
            raise CommandError(
                'unknown type name, type must be one of [topic, tag, itemwiki, diary, service, doctor, user, _all]，ItemWiki,newwiki')

        es = get_es()

        type_mapping = {
            'topic': 'problem',
            'tag': 'tag',
            'itemwiki': 'itemwiki',
            'diary': 'diary',
            'service': 'service',
            'doctor': 'doctor',
            'user': 'user',
            'question': 'question',
            'board': 'board',
            'answer': 'answer',
            'article': 'article',
            'sku': 'sku',
            'diary_norms_disable': 'diary_norms_disable',
            'service_norms_disable': 'service_norms_disable',
            'newwiki': 'newwiki',
            "wiki_keyword": "wiki_keyword",
            "qa_top": "qa_top",
            "subscript_article": "subscript_article",
            "tractate": "tractate",
            "doctortractate": "doctortractate",
            "service_ngram": "service_ngram",
            "principal": "principal",
            "user_album": "user_album"

        }

        if options['index_prefix']:
            index_prefix = options['index_prefix']
        else:
            index_prefix = settings.ES_INDEX_PREFIX

        if options['index_version']:
            index_prefix += '-' + options['index_version']

        if options['type'] == '_all':
            for doc_type in type_mapping.values():
                if doc_type not in ["diary_norms_disable", "service_norms_disable"]:
                    self.work(es=es, index_prefix=index_prefix, doc_type=doc_type,
                              delete=options['delete'])
        else:
            self.work(es=es, index_prefix=index_prefix, doc_type=type_mapping[options['type']],
                      delete=options['delete'])

    def work(self, es, index_prefix, doc_type, delete=False):
        # create index if not exits
        create_index(es=es, index_prefix=index_prefix, doc_type=doc_type)

        m = load_mapping(doc_type=doc_type)

        # reset doc_type for experiment index
        if doc_type == "diary_norms_disable":
            doc_type = "diary"
        if doc_type == "sku_norms_disable":
            doc_type = "sku"
        if doc_type == "service_norms_disable":
            doc_type = "service"
        if doc_type == "service_ngram":
            doc_type = "service"
        print(put_mapping(es=es, index_prefix=index_prefix, doc_type=doc_type,
                          mapping=m, delete=delete))
