#!/usr/bin/env python3

from __future__ import print_function

import os, sys
import glob, json
import configparser
from urllib3 import exceptions as ul_excs, Timeout
from elasticsearch import VERSION, Elasticsearch, exceptions as es_excs

# ES config
host = "10.12.23.122"
port = 9201
hosts = [dict(host=host, port=port),]
auth = ('admin', 'admin')
es = Elasticsearch(hosts,
        max_retries=0,
        http_auth=auth)

INDEX_PREFIX = 'cfme-run'
CFME_TEMPLATE_VERSION = '02'
NUMBER_OF_SHARDS = 1
NUMBER_OF_REPLICAS = 5

_read_timeout = 120
timeoutobj = Timeout(total=1200, connect=10, read=_read_timeout)

settings = {}
# settings['number_of_shards'] = NUMBER_OF_SHARDS
# settings['number_of_replicas'] = NUMBER_OF_REPLICAS


BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
LIBDIR = os.path.join(BASE_DIR, 'mappings')


def fetch_mapping(mapping_fn):
    with open(mapping_fn, "r") as mappingfp:
        try:
            mapping = json.load(mappingfp)
        except ValueError as err:
            print("%s: %s" % (mapping_fn, err), file=sys.stderr)
            sys.exit(1)
    return mapping

def create_template(tname, tbody):
    if es.indices.exists_template(name=tname):
        print("template %s exists" % tname)
        return
    try:
        res = es.indices.put_template(name=tname, body=tbody)
    except Exception as err:
        print(repr(err), file=sys.stderr)
        sys.exit(1)
    else:
        try:
            if not res['acknowledged']:
                print('ERROR - Template creation was not acknowledged', file=sys.stderr)
                sys.exit(1)
        except KeyError:
            print('ERROR - Template creation failed: %r' % res, file=sys.stderr)
            sys.exit(1)
        print("Created template %s" % tname)


def init_upload(index_type, doc_type):
    _mappings = fetch_mapping(os.path.join(LIBDIR, "%s.json" % doc_type))
    _settings = settings
    smem_body = dict(
        template='%s.%s-*' % (INDEX_PREFIX, index_type),
        settings=_settings,
        mappings=_mappings)
    tname = '%s.%s-%s' % (INDEX_PREFIX, index_type, CFME_TEMPLATE_VERSION)
    smem_body['template'] = '%s.%s-*' % (INDEX_PREFIX, index_type)
    create_template(tname, smem_body)

if __name__ == '__main__':
    init_upload('smem', 'smem')
    init_upload('summary', 'metadata')
