import requests
import json
from server_modules.util import *
import sys, traceback
import copy

def get_info(easydb_context, db_cursor, config, instance, loggername):
	es_url = get_config(config, 'system/elasticsearch/url')
	es_index = instance['name']
	es_index = instance['db-name']
	data = []
	general_info = {
		'headers': {
			'values': [
				'Server URL', 'Index Name', 'Cluster Name', 'Cluster Status', 'Index Docs', 'Index Size', 'Nodes Count'
			],
			'name': 'name'
		},
		'type': '2d-map',
		'name': 'general',
		'data': [ {
			'values': [ es_url, es_index ],
			'type': 'string',
			'name': 'value'
		} ]
	}
	try:
		r = requests.get('{0}/_cluster/health'.format(es_url))
		if r.status_code != 200:
			raise Exception('Elasticsearch cluster health request returned {0}: {1}'.format(r.status_code, r.text))
		es_info = json.loads(r.text)
		general_info['data'][0]['values'].append(es_info['cluster_name'])
		general_info['data'][0]['values'].append(es_info['status'] + ' color')

		r = requests.get('{0}/{1}/_stats'.format(es_url, es_index))
		if r.status_code != 200:
			raise Exception('Elasticsearch index stats request returned {0}: {1}'.format(r.status_code, r.text))
		es_stats = json.loads(r.text)['indices'][es_index]['total']
		general_info['data'][0]['values'].append(str(es_stats['docs']['count']))
		general_info['data'][0]['values'].append(str(es_stats['store']['size_in_bytes']) + ' bytes')

		r = requests.get('{0}/_nodes/stats'.format(es_url))
		if r.status_code != 200:
			raise Exception('Elasticsearch nodes stats request returned {0}: {1}'.format(r.status_code, r.text))
		nodes_stats = json.loads(r.text)
		nodes = list(nodes_stats['nodes'].keys())
		general_info['data'][0]['values'].append(str(len(nodes)))

		data.append(general_info)

		node_info = {
			'headers': {
				'values': [ 'Node #', 'Node UID', 'Node Name', 'Index Docs', 'Index Size', 'HTTP Connections', 'File System Free',
					'Load Average (last 1, 5, 15 minutes)', 'CPU Idle', 'Memory Used', 'Memory Free' ],
				'name': 'node'
			},
			'type': '2d-map',
			'name': 'node',
			'data': [ {
				'values': [],
				'type': 'string',
				'name': 'value'
			} ]
		}

		node_n = 1
		for node in nodes:
			info = nodes_stats['nodes'][node]
			n = copy.deepcopy(node_info)
			n['data'][0]['values'].append(str(node_n))
			n['data'][0]['values'].append(node)
			n['data'][0]['values'].append(info["name"])
			n['data'][0]['values'].append(str(info["indices"]["docs"]["count"]))
			n['data'][0]['values'].append(str(info["indices"]["store"]["size_in_bytes"]) + ' bytes')
			n['data'][0]['values'].append(str(info["http"]["current_open"]))
			n['data'][0]['values'].append(str(info["fs"]["total"]["available_in_bytes"]) + ' bytes')
			n['data'][0]['values'].append(
				str(info["os"]["cpu"]["load_average"]["1m"]) + ', ' +
				str(info["os"]["cpu"]["load_average"]["5m"]) + ', ' +
				str(info["os"]["cpu"]["load_average"]["15m"])
			)
			n['data'][0]['values'].append(str(info["os"]["cpu"]["percent"]) + ' %')
			n['data'][0]['values'].append(str(info["os"]["mem"]["used_percent"]) + ' %')
			n['data'][0]['values'].append(str(info["os"]["mem"]["free_percent"]) + ' %')
			node_n = node_n + 1
			data.append(n)

	except Exception as e:
		data.append(make_error('connect-error', 'error.server', str(e)))
	return data
