# coding=utf-8
from __future__ import absolute_import, unicode_literals
from django.core.management.base import BaseCommand, CommandError


from message.utils.es_abstract import create_esop_for_database, table_schema_map


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

    from optparse import make_option
    option_list = BaseCommand.option_list + (
        make_option('--database', dest='database',
                    help='database name to dump data to elasticsearch', metavar='DATABASE'),
        make_option('--table', dest='table', help='table name to dump data to elasticsearch', metavar='TABLE'),
        make_option('-d', '--delete', dest='delete', action='store_true', default=False,
                    help='whether to delete original mapping with its data'),
    )

    def handle(self, *args, **options):
        ALL = '_all'

        option_database = options['database']
        option_table = options['table']

        if not option_database:
            raise CommandError('database name must be specified')

        if not option_table:
            raise CommandError('table name must be specified')
        elif not options['table'] in list(table_schema_map) + [ALL]:
            raise CommandError('unknown table name, table must be one of [message]')

        if option_table == ALL:
            table_name_list = list(table_schema_map.keys())
        else:
            table_name_list = [option_table]

        esop = create_esop_for_database(option_database)
        for table_name in table_name_list:
            table = table_schema_map[table_name]
            print(esop.alter_table(table=table, drop_if_exists=options['delete']))
