# Path: myDevices/utils/logger.py
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# def info(message):
#     # if checkFlood(message):
#     #     return
#     LOGGER.info(message)
# 
# def warn(message):
#     if checkFlood(message):
#         return
#     LOGGER.warn(message)
# 
# def error(message, *args, **kwargs):
#     if checkFlood(message):
#         return
#     LOGGER.error(message, *args, **kwargs)
# 
# def debug(message):
#     outerFrame = getouterframes(currentframe())[1][0]
#     (args, _, _, values) = getargvalues(outerFrame)
#     argsValue = ''
#     
#     for i in args:
#         if i is 'self':
#             continue
#         argsValue += "(%s=%s)" % (i, str(values[i]))
#     
#     stack = extract_stack()
#     (filename, line, procname, text) = stack[-2]
#     LOGGER.debug(str(filename) + ' ' + str(procname) + str(argsValue) + ':' + str(line) + '> '  + str(message))
# 
# def setDebug():
#     LOGGER.setLevel(DEBUG)
#     return
# 
# def logJson(message, category = ''):
#     if debugEnabled() == False:
#         return
#     if checkFlood(message):
#         return
#     try:
#         if category not in jsonData:
#             jsonData[category] = []
#         if len(jsonData[category]) > MAX_JSON_ITEMS_PER_CATEGORY:
#             del jsonData[category][0]
#         #2016-03-23 03:53:16 - myDevices - INFO -
#         message = str(datetime.today()) + ' - myDevices - INFO - ' + message
#         jsonData[category].append(message)
#         rotatorJson()
#     except Exception as ex:
#         exception("logJson failed")


from myDevices.utils.logger import exception, info, warn, error, debug, setDebug, logJson
from json import loads, dumps
from time import time
from datetime import datetime, timedelta
from sqlite3 import connect
from operator import itemgetter
from os import rename
from sys import argv
            try:
                current_avgs['SystemInfo']['Cpu']['temperature'] = self.CalculateAverage(current_avgs['SystemInfo']['Cpu']['temperature'], new_sample['SystemInfo']['Cpu']['temperature'], count)
            except:
                exception('Error calculating CPU temperature average')
            #Calculate network averages
            try:
                for key in ('packets', 'bytes'):
                    for subkey in new_sample['SystemInfo']['Network'][key].keys():
                        current_avgs['SystemInfo']['Network'][key][subkey] = self.CalculateSubItemAverages(current_avgs['SystemInfo']['Network'][key][subkey], new_sample['SystemInfo']['Network'][key][subkey], count)
            except:
                # Ignore error if key doesn't exist
                pass
            #Calculate storage averages
            try:
                for subkey in new_sample['SystemInfo']['Storage']['throughput'].keys():
                    current_avgs['SystemInfo']['Storage']['throughput'][subkey] = self.CalculateSubItemAverages(current_avgs['SystemInfo']['Storage']['throughput'][subkey], new_sample['SystemInfo']['Storage']['throughput'][subkey], count)
            except:
                # Ignore error if one of the dicts doesn't contain 'throughput'
                pass
            current_avgs['SystemInfo']['Storage']['list'] = self.CalculateListAverages(current_avgs['SystemInfo']['Storage']['list'], new_sample['SystemInfo']['Storage']['list'], ('available', 'used', 'use'), 'mount', count)
            #Calculate memory averages
            current_avgs['SystemInfo']['Memory'] = self.CalculateSubItemAverages(current_avgs['SystemInfo']['Memory'], new_sample['SystemInfo']['Memory'], count)
            #Totals don't get averaged, they are just copied
            current_avgs['SystemInfo']['Memory']['total'] = new_sample['SystemInfo']['Memory']['total']
            current_avgs['SystemInfo']['Memory']['swap']['total'] = new_sample['SystemInfo']['Memory']['swap']['total']
        except:
            exception('Error calculating system info averages: current_avgs {}, new_sample {} '.format(current_avgs, new_sample))
        
    def CalculateSensorsInfoAverages(self, current_avgs, new_sample, count_sensor):
        try:

# Path: myDevices/utils/logger.py
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# def info(message):
#     # if checkFlood(message):
#     #     return
#     LOGGER.info(message)
# 
# def warn(message):
#     if checkFlood(message):
#         return
#     LOGGER.warn(message)
# 
# def error(message, *args, **kwargs):
#     if checkFlood(message):
#         return
#     LOGGER.error(message, *args, **kwargs)
# 
# def debug(message):
#     outerFrame = getouterframes(currentframe())[1][0]
#     (args, _, _, values) = getargvalues(outerFrame)
#     argsValue = ''
#     
#     for i in args:
#         if i is 'self':
#             continue
#         argsValue += "(%s=%s)" % (i, str(values[i]))
#     
#     stack = extract_stack()
#     (filename, line, procname, text) = stack[-2]
#     LOGGER.debug(str(filename) + ' ' + str(procname) + str(argsValue) + ':' + str(line) + '> '  + str(message))
# 
# def setDebug():
#     LOGGER.setLevel(DEBUG)
#     return
# 
# def logJson(message, category = ''):
#     if debugEnabled() == False:
#         return
#     if checkFlood(message):
#         return
#     try:
#         if category not in jsonData:
#             jsonData[category] = []
#         if len(jsonData[category]) > MAX_JSON_ITEMS_PER_CATEGORY:
#             del jsonData[category][0]
#         #2016-03-23 03:53:16 - myDevices - INFO -
#         message = str(datetime.today()) + ' - myDevices - INFO - ' + message
#         jsonData[category].append(message)
#         rotatorJson()
#     except Exception as ex:
#         exception("logJson failed")


# Path: myDevices/utils/history.py
from myDevices.utils.logger import exception, info, warn, error, debug, setDebug, logJson
from json import loads, dumps
from time import time
from datetime import datetime, timedelta
from sqlite3 import connect
from operator import itemgetter
from os import rename
from sys import argv

            try:
                current_avgs['SystemInfo']['Cpu']['temperature'] = self.CalculateAverage(current_avgs['SystemInfo']['Cpu']['temperature'], new_sample['SystemInfo']['Cpu']['temperature'], count)
            except:
                exception('Error calculating CPU temperature average')
            #Calculate network averages
            try:
                for key in ('packets', 'bytes'):
                    for subkey in new_sample['SystemInfo']['Network'][key].keys():
                        current_avgs['SystemInfo']['Network'][key][subkey] = self.CalculateSubItemAverages(current_avgs['SystemInfo']['Network'][key][subkey], new_sample['SystemInfo']['Network'][key][subkey], count)
            except:
                # Ignore error if key doesn't exist
                pass
            #Calculate storage averages
            try:
                for subkey in new_sample['SystemInfo']['Storage']['throughput'].keys():
                    current_avgs['SystemInfo']['Storage']['throughput'][subkey] = self.CalculateSubItemAverages(current_avgs['SystemInfo']['Storage']['throughput'][subkey], new_sample['SystemInfo']['Storage']['throughput'][subkey], count)
            except:
                # Ignore error if one of the dicts doesn't contain 'throughput'
                pass
            current_avgs['SystemInfo']['Storage']['list'] = self.CalculateListAverages(current_avgs['SystemInfo']['Storage']['list'], new_sample['SystemInfo']['Storage']['list'], ('available', 'used', 'use'), 'mount', count)
            #Calculate memory averages
            current_avgs['SystemInfo']['Memory'] = self.CalculateSubItemAverages(current_avgs['SystemInfo']['Memory'], new_sample['SystemInfo']['Memory'], count)
            #Totals don't get averaged, they are just copied
            current_avgs['SystemInfo']['Memory']['total'] = new_sample['SystemInfo']['Memory']['total']
            current_avgs['SystemInfo']['Memory']['swap']['total'] = new_sample['SystemInfo']['Memory']['swap']['total']
        except:
            exception('Error calculating system info averages: current_avgs {}, new_sample {} '.format(current_avgs, new_sample))
        
    def CalculateSensorsInfoAverages(self, current_avgs, new_sample, count_sensor):
        try:

            logJson('History SensorsInfo average: '  + str(new_sample), 'history')