# Path: stack_configs/influx_functions.py
# def sendToInflux(indexName,jsonData,tags):   
#     
#     client=getInfluxConnection()
#     
#     
#     '''for each field in jsonData if timestamp-pass with reserved key "time"
#     if float, convert, otherwise pass as string field
#     everything else treat as tag'''
#     #jsonData={"timestamp":'2009-11-10T23:00:00Z',"value":0.44}
#     f={}
#     d={}             
#     for key, value in list(jsonData.items()):
#         if (key=='timestamp'):
#             d["time"]= value
#         else:
#             try:
#                 f[key]=float(value)  
#             except:
#                 f[key]=value
#    
#     #d = {}
#     d["measurement"] = "mqttData"
#     d["tags"] = tags
#     #d["time"] = "2009-11-10T23:00:00Z"
#     d["fields"] = f
#     #below for debugging 
#     json_tags = json.dumps(tags,default=date_handler)
#     json_fields = json.dumps(f,default=date_handler)
#     logger.debug('tags %s', json_tags)   
#     logger.debug('fields %s', json_fields)
#     #above for statements for debugging only
#     json_body=[d]
#     logger.debug('trying db create') 
#        
#     try:
#         res=client.write_points(json_body,database=indexName)
#         logger.info('influx write result %s,', res) 
#     except Exception as e: 
#         logger.warning('couldnt write to database %s,', e) 
#     #result = client.query('select value from cpu_load_short;')
#         res=e    
#     logger.warning('returning res %s,', res)     
#     return res


from builtins import str
from django.db import models
from django.core.exceptions import ValidationError
from datetime import datetime
from django.conf import settings
from elasticsearch import Elasticsearch
from genericpath import exists
from django.contrib.admin.utils import help_text_for_field
from influxdb import InfluxDBClient,SeriesHelper
from .influx_functions import sendToInflux
import pika
import ssl
import json
import logging


def getElasticConnection():
    config=settings.ELASTICSEARCH
    es = Elasticsearch([config['host']],
                           http_auth=(config['user'], config['password']),
                           port=config['port'],
                           use_ssl=config['use_ssl'],
                           ca_certs=config['path_to_ca_cert'],
                           client_cert=config['path_to_client_cert'],
                           client_key=config['path_to_key'])
    return es  


    
def sendToElastic(indexName,jsonData):    
#careful with document types! currently static as json mapping must also use json!        
        es = getElasticConnection()
        res = es.index(index=indexName, doc_type="json", body=jsonData)
        return res
        
        #except:
        #    return False
def searchElastic(indexName,query):
        
        
        es = getElasticConnection()
                  
        try:
            res = es.search(index=indexName, body=query)

# Path: stack_configs/influx_functions.py
# def sendToInflux(indexName,jsonData,tags):   
#     
#     client=getInfluxConnection()
#     
#     
#     '''for each field in jsonData if timestamp-pass with reserved key "time"
#     if float, convert, otherwise pass as string field
#     everything else treat as tag'''
#     #jsonData={"timestamp":'2009-11-10T23:00:00Z',"value":0.44}
#     f={}
#     d={}             
#     for key, value in list(jsonData.items()):
#         if (key=='timestamp'):
#             d["time"]= value
#         else:
#             try:
#                 f[key]=float(value)  
#             except:
#                 f[key]=value
#    
#     #d = {}
#     d["measurement"] = "mqttData"
#     d["tags"] = tags
#     #d["time"] = "2009-11-10T23:00:00Z"
#     d["fields"] = f
#     #below for debugging 
#     json_tags = json.dumps(tags,default=date_handler)
#     json_fields = json.dumps(f,default=date_handler)
#     logger.debug('tags %s', json_tags)   
#     logger.debug('fields %s', json_fields)
#     #above for statements for debugging only
#     json_body=[d]
#     logger.debug('trying db create') 
#        
#     try:
#         res=client.write_points(json_body,database=indexName)
#         logger.info('influx write result %s,', res) 
#     except Exception as e: 
#         logger.warning('couldnt write to database %s,', e) 
#     #result = client.query('select value from cpu_load_short;')
#         res=e    
#     logger.warning('returning res %s,', res)     
#     return res


# Path: stack_configs/models.py
from builtins import str
from django.db import models
from django.core.exceptions import ValidationError
from datetime import datetime
from django.conf import settings
from elasticsearch import Elasticsearch
from genericpath import exists
from django.contrib.admin.utils import help_text_for_field
from influxdb import InfluxDBClient,SeriesHelper
from .influx_functions import sendToInflux
import pika
import ssl
import json
import logging



def getElasticConnection():
    config=settings.ELASTICSEARCH
    es = Elasticsearch([config['host']],
                           http_auth=(config['user'], config['password']),
                           port=config['port'],
                           use_ssl=config['use_ssl'],
                           ca_certs=config['path_to_ca_cert'],
                           client_cert=config['path_to_client_cert'],
                           client_key=config['path_to_key'])
    return es  


    
def sendToElastic(indexName,jsonData):    
#careful with document types! currently static as json mapping must also use json!        
        es = getElasticConnection()
        res = es.index(index=indexName, doc_type="json", body=jsonData)
        return res
        
        #except:
        #    return False
def searchElastic(indexName,query):
        
        
        es = getElasticConnection()
                  
        try:
            res = es.search(index=indexName, body=query)

            return res