# Path: myDevices/utils/logger.py
# 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 error(message, *args, **kwargs):
#     if checkFlood(message):
#         return
#     LOGGER.error(message, *args, **kwargs)
# 
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# def info(message):
#     # if checkFlood(message):
#     #     return
#     LOGGER.info(message)
# 
# 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")
# 
# def setDebug():
#     LOGGER.setLevel(DEBUG)
#     return
# 
# def warn(message):
#     if checkFlood(message):
#         return
#     LOGGER.warn(message)


from datetime import datetime
from json import dumps, loads
from sqlite3 import connect
from threading import RLock, Thread
from time import sleep
from myDevices.requests_futures.sessions import FuturesSession
from myDevices.utils.logger import debug, error, exception, info, logJson, setDebug, warn
import myDevices.schedule as schedule



class SchedulerEngine(Thread):
    """Class that creates the scheduler and launches scheduled actions"""

    def __init__(self, client, name):
        """Initialize the scheduler and start the scheduler thread
        
        client: the client running the scheduler
        name: name to use for the scheduler thread"""
        self.connection = connect('/etc/myDevices/agent.db', check_same_thread = False)
        self.cursor = self.connection.cursor()
        self.cursor.execute('CREATE TABLE IF NOT EXISTS scheduled_events (id TEXT PRIMARY KEY, event TEXT)')
        Thread.__init__(self, name=name)
        self.mutex = RLock()
        self.schedule_items = {}
        self.client = client
        self.running = False
        self.load_schedule()
        self.start()

    def __del__(self):
        """Delete scheduler object"""
        try:
            self.connection.close()
        except:

# Path: myDevices/utils/logger.py
# 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 error(message, *args, **kwargs):
#     if checkFlood(message):
#         return
#     LOGGER.error(message, *args, **kwargs)
# 
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# def info(message):
#     # if checkFlood(message):
#     #     return
#     LOGGER.info(message)
# 
# 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")
# 
# def setDebug():
#     LOGGER.setLevel(DEBUG)
#     return
# 
# def warn(message):
#     if checkFlood(message):
#         return
#     LOGGER.warn(message)


# Path: myDevices/cloud/scheduler.py
from datetime import datetime
from json import dumps, loads
from sqlite3 import connect
from threading import RLock, Thread
from time import sleep
from myDevices.requests_futures.sessions import FuturesSession
from myDevices.utils.logger import debug, error, exception, info, logJson, setDebug, warn
import myDevices.schedule as schedule




class SchedulerEngine(Thread):
    """Class that creates the scheduler and launches scheduled actions"""

    def __init__(self, client, name):
        """Initialize the scheduler and start the scheduler thread
        
        client: the client running the scheduler
        name: name to use for the scheduler thread"""
        self.connection = connect('/etc/myDevices/agent.db', check_same_thread = False)
        self.cursor = self.connection.cursor()
        self.cursor.execute('CREATE TABLE IF NOT EXISTS scheduled_events (id TEXT PRIMARY KEY, event TEXT)')
        Thread.__init__(self, name=name)
        self.mutex = RLock()
        self.schedule_items = {}
        self.client = client
        self.running = False
        self.load_schedule()
        self.start()

    def __del__(self):
        """Delete scheduler object"""
        try:
            self.connection.close()
        except:

            exception('Error deleting SchedulerEngine')