#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from elasticsearch import Elasticsearch as Es
from trans2es.utils.es import get_es, put_mapping, load_mapping, create_index, reindex, alias_shift

class Command(BaseCommand):
    """DERPECATED
    """
    args = ''
    help = 'migrate from old index to new index elasticsearch'

    from optparse import make_option
    option_list = BaseCommand.option_list + ( 
        make_option('-f', '--from', dest='from_index', help='index name to dump from', metavar='FROM'),
        make_option('-t', '--to', dest='to_index', help='index name to dump to', metavar='TO'),
    )

    def handle(self, *args, **options):
        if not options['from_index'] or not options['to_index']:
            raise CommandError('"from index" and "to index" must be both specified')

        es = get_es()

        # create to_index first
        create_index(es=es, index=options['to_index'])

        # then create mapping
        type_mapping = {
            'topic':'problem',
            'tag':'tag',
            'itemwiki':'itemwiki',
            'diary':'diary',
            'service':'service',
            'doctor':'doctor',
            'board':'board',
        }
        for type in type_mapping.values():
            m = load_mapping(type=type)
            put_mapping(es=es, index=options['to_index'], type=type, mapping=m)

        # write alias shift
        alias_shift(es=es, alias=settings.ES_WRITE_INDEX, old_index=options['from_index'], new_index=options['to_index'])

        # reindex
        reindex(es=es, old_index=options['from_index'], new_index=options['to_index'])

        # read alias shift
        alias_shift(es=es, alias=settings.ES_READ_INDEX, old_index=options['from_index'], new_index=options['to_index'])

        # delete old index
