# 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))
# 
# Path: myDevices/utils/daemon.py
# class Daemon:
#     """class for restarting the agent if errors occur and exiting on critical failures."""
# 
#     @staticmethod
#     def OnFailure(component, error=0):
#         """Handle error in component and restart the agent if necessary"""
#         #-3=Temporary failure in name resolution
#         info('Daemon failure handling ' + str(error))
#         if error in errorList:
#             Daemon.Restart()
#         if component not in failureCount:
#             Daemon.Reset(component)
#         failureCount[component] += 1
#         now = datetime.now()
#         if startFailure[component] == 0:
#             startFailure[component] = now
#         elapsedTime = now - startFailure[component]
#         if (elapsedTime.total_seconds() >= RESET_TIMEOUT) or (failureCount[component] > FAILURE_COUNT):
#             warn('Daemon::OnFailure myDevices is going to restart after ' + str(component) + ' failed: ' + str(elapsedTime.total_seconds()) + ' seconds and ' + str(failureCount) + ' times')
#             Daemon.Restart()
# 
#     @staticmethod
#     def Reset(component):
#         """Reset failure count for component"""
#         startFailure[component] = 0
#         failureCount[component] = 0
# 
#     @staticmethod
#     def Restart():
#         """Restart the agent daemon"""
#         try:
#             info('Daemon restarting myDevices' )
#             (output, returncode) = executeCommand('sudo service myDevices restart')
#             debug(str(output) + ' ' + str(returncode))
#             del output
#         except:
#             exception("Daemon::Restart unexpected error")
#             Daemon.Exit()
# 
#     @staticmethod
#     def Exit():
#         """Stop the agent daemon"""
#         error('Critical failure. Closing myDevices process.')
#         raise SystemExit
# 
# Path: myDevices/utils/threadpool.py
# class ThreadPool(Singleton):
#     """Singleton thread pool class"""
# 
#     @staticmethod
#     def Submit(func):
#         """Submit a function for the thread pool to run"""
#         executor.submit(func)
# 
#     @staticmethod
#     def Shutdown():
#         """Shutdown the thread pool"""
#         executor.shutdown()


from datetime import datetime, timedelta
from os import path, remove
from urllib import request, error
from myDevices.utils.logger import exception, info, warn, error, debug
from time import sleep
from random import randint
from socket import error as socket_error
from myDevices.utils.daemon import Daemon
from myDevices.utils.threadpool import ThreadPool
    from myDevices.utils.config import Config    
"""
This module provides a class for testing download speed
"""

defaultUrl = "https://updates.mydevices.com/test/10MB.zip"
download_path = "/etc/myDevices/test"
mb = 1024*1024
#in seconds download Rate = 24 hours
defaultDownloadRate = 24*60*60

class DownloadSpeed():
    """Class for checking download speed"""

    def __init__(self, config):
        """Initialize variables and start download speed test"""
        self.downloadSpeed = None
        self.testTime = None
        self.isRunning = False
        self.Start()
        self.config = config
        #add a random delay to the start of download 
        self.delay = randint(0, 100)

    def Start(self):
        """Start download speed thread"""

# 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))
# 
# Path: myDevices/utils/daemon.py
# class Daemon:
#     """class for restarting the agent if errors occur and exiting on critical failures."""
# 
#     @staticmethod
#     def OnFailure(component, error=0):
#         """Handle error in component and restart the agent if necessary"""
#         #-3=Temporary failure in name resolution
#         info('Daemon failure handling ' + str(error))
#         if error in errorList:
#             Daemon.Restart()
#         if component not in failureCount:
#             Daemon.Reset(component)
#         failureCount[component] += 1
#         now = datetime.now()
#         if startFailure[component] == 0:
#             startFailure[component] = now
#         elapsedTime = now - startFailure[component]
#         if (elapsedTime.total_seconds() >= RESET_TIMEOUT) or (failureCount[component] > FAILURE_COUNT):
#             warn('Daemon::OnFailure myDevices is going to restart after ' + str(component) + ' failed: ' + str(elapsedTime.total_seconds()) + ' seconds and ' + str(failureCount) + ' times')
#             Daemon.Restart()
# 
#     @staticmethod
#     def Reset(component):
#         """Reset failure count for component"""
#         startFailure[component] = 0
#         failureCount[component] = 0
# 
#     @staticmethod
#     def Restart():
#         """Restart the agent daemon"""
#         try:
#             info('Daemon restarting myDevices' )
#             (output, returncode) = executeCommand('sudo service myDevices restart')
#             debug(str(output) + ' ' + str(returncode))
#             del output
#         except:
#             exception("Daemon::Restart unexpected error")
#             Daemon.Exit()
# 
#     @staticmethod
#     def Exit():
#         """Stop the agent daemon"""
#         error('Critical failure. Closing myDevices process.')
#         raise SystemExit
# 
# Path: myDevices/utils/threadpool.py
# class ThreadPool(Singleton):
#     """Singleton thread pool class"""
# 
#     @staticmethod
#     def Submit(func):
#         """Submit a function for the thread pool to run"""
#         executor.submit(func)
# 
#     @staticmethod
#     def Shutdown():
#         """Shutdown the thread pool"""
#         executor.shutdown()


# Path: myDevices/cloud/download_speed.py
from datetime import datetime, timedelta
from os import path, remove
from urllib import request, error
from myDevices.utils.logger import exception, info, warn, error, debug
from time import sleep
from random import randint
from socket import error as socket_error
from myDevices.utils.daemon import Daemon
from myDevices.utils.threadpool import ThreadPool
    from myDevices.utils.config import Config    

"""
This module provides a class for testing download speed
"""

defaultUrl = "https://updates.mydevices.com/test/10MB.zip"
download_path = "/etc/myDevices/test"
mb = 1024*1024
#in seconds download Rate = 24 hours
defaultDownloadRate = 24*60*60

class DownloadSpeed():
    """Class for checking download speed"""

    def __init__(self, config):
        """Initialize variables and start download speed test"""
        self.downloadSpeed = None
        self.testTime = None
        self.isRunning = False
        self.Start()
        self.config = config
        #add a random delay to the start of download 
        self.delay = randint(0, 100)

    def Start(self):
        """Start download speed thread"""

        ThreadPool.Submit(self.Test)