# 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
            self.count_sensor['SensorsInfo'] = {}
            self.id = None
            self.start_time = time()
            self.end_time = None
            self.connection = connect('/etc/myDevices/agent.db', check_same_thread = False)
            self.cursor = self.connection.cursor()
            self.cursor.execute('PRAGMA table_info(historical_averages)')
            actual_columns = [column[1] for column in self.cursor.fetchall()]
            # required_columns = ['id', 'data', 'count', 'start', 'end', 'interval', 'send', 'count_sensor']
            # if actual_columns != required_columns:
            #     try:
            #         warn('historical_averages table columns {} do not match required columns {}, dropping table'.format(actual_columns, required_columns))
            #         self.cursor.execute('DROP TABLE historical_averages')
            #         self.connection.commit()
            #     except:
            #         pass
            # self.cursor.execute('CREATE TABLE IF NOT EXISTS historical_averages (id INTEGER PRIMARY KEY, data TEXT, count INTEGER, start TIMESTAMP, end TIMESTAMP, interval TEXT, send TEXT, count_sensor TEXT)')
            self.cursor.execute('SELECT * FROM historical_averages WHERE interval = ? ORDER BY end DESC LIMIT 1', (History.RUNNING,))
            results = self.cursor.fetchall()
            for row in results:
                self.id = row[0]
                self.avg_values = loads(row[1])
                self.count = row[2]
                self.start_time = row[3]
                self.end_time = row[4]
                self.count_sensor = loads(row[7])
            del actual_columns
            #del required_columns

        except:

# 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

            self.count_sensor['SensorsInfo'] = {}
            self.id = None
            self.start_time = time()
            self.end_time = None
            self.connection = connect('/etc/myDevices/agent.db', check_same_thread = False)
            self.cursor = self.connection.cursor()
            self.cursor.execute('PRAGMA table_info(historical_averages)')
            actual_columns = [column[1] for column in self.cursor.fetchall()]
            # required_columns = ['id', 'data', 'count', 'start', 'end', 'interval', 'send', 'count_sensor']
            # if actual_columns != required_columns:
            #     try:
            #         warn('historical_averages table columns {} do not match required columns {}, dropping table'.format(actual_columns, required_columns))
            #         self.cursor.execute('DROP TABLE historical_averages')
            #         self.connection.commit()
            #     except:
            #         pass
            # self.cursor.execute('CREATE TABLE IF NOT EXISTS historical_averages (id INTEGER PRIMARY KEY, data TEXT, count INTEGER, start TIMESTAMP, end TIMESTAMP, interval TEXT, send TEXT, count_sensor TEXT)')
            self.cursor.execute('SELECT * FROM historical_averages WHERE interval = ? ORDER BY end DESC LIMIT 1', (History.RUNNING,))
            results = self.cursor.fetchall()
            for row in results:
                self.id = row[0]
                self.avg_values = loads(row[1])
                self.count = row[2]
                self.start_time = row[3]
                self.end_time = row[4]
                self.count_sensor = loads(row[7])
            del actual_columns
            #del required_columns

        except:

            exception('Error creating History object')