#!/usr/bin/env python3

import time

import requests

# Wait 
# time.sleep(90)

auth = requests.auth.HTTPBasicAuth("elastic", "changeme")


def check_elastic():
    response = None
    try:
        response = requests.get("http://localhost:9200/_cluster/health", auth=auth)
    except requests.ConnectionError:
        return False

    return response.status_code == 200


def set_index(url: str, file: str):
    with open(file, 'r') as f:
        data = f.read()
    headers = {'Content-Type': 'application/json'}
    response = requests.put(url, headers=headers, auth=auth, data=data)

    return response.status_code == 200 and response.json()['acknowledged'] == True


# Wait for elastic ready
counter = 0
while counter < 100:
    if not check_elastic():
        time.sleep(1)
    else:
        break

print("Installing index")

data = [
    {"url": "http://localhost:9200/_component_template/normalized_component",
     "file": "../compose/config/elk/elasticsearch/mapping/normalized-component.json"},
    {"url": "http://localhost:9200/_index_template/normalized",
     "file": "../compose/config/elk/elasticsearch/mapping/normalized-index-template.json"},
    {"url": "http://localhost:9200/_component_template/aggregated_component",
     "file": "../compose/config/elk/elasticsearch/mapping/aggregated-component.json"},
    {"url": "http://localhost:9200/_index_template/aggregated",
     "file": "../compose/config/elk/elasticsearch/mapping/aggregated-index-teplate.json"},
]

for cur in data:
    if not set_index(cur['url'], cur['file']):
        print(f"Can't set index {cur['file']}")
        exit(1)

print("All done")
exit(0)
