# Path: lib/loghelper.py
# class Logger():
#     """
#     Think of this class like a light interface
#     """
# 
#     def __init__(self, method=""):
#         self.instance = _LoggerSingleton()
#         self.method = method
# 
#     def setup(self, **kwargs):
#         self.instance.setup(**kwargs)
# 
#     def print_(self, message, **kwargs):
#         self.instance.logprint(message, **kwargs)
# 
#     def debug(self, *args):
#         """
#         This works a little differently. You can basically throw anything you want into it.
#         :param message:
#         :return:
#         """
#         msgarr =  []
#         for arg in args:
#             if type(arg) is str:
#                 msgarr.append(arg)
#             else:
#                 msgarr.append(pformat(arg))
#         finalmessage = '\n'.join(msgarr).replace('\n', '\n              ')
#         self.instance.logprint(finalmessage, self.method, "debug")
# 
#     def destroy(self):
#         self.instance = None
#         self.method = None
# 
#     def info(self, message):
#         self.instance.logprint(message, self.method, "info")
# 
#     def error(self, message, exception=None):
#         self.instance.logprint(message, self.method, "error", exception)
# 
#     def warning(self, message, exception=None):
#         self.instance.logprint(message, self.method, "warning", exception)
# 
# Path: lib/sitkaAPI.py
# def APIGet(url, absolute=False):
#     """
#     GET Wrapper around APIGet
#     :param url:
#     :param absolute:
#     :return:
#     """
#     log = Logger("APIGet")
#     #log.info("Making Call: GET {}".format(url))
#     return APICall(url, absolute, method=requests.get)
# 
# Path: lib/progressbar.py
# class ProgressBar(object):
#     """ProgressBar class holds the options of the progress bar.
#     The options are:
#         start   State from which start the progress. For example, if start is
#                 5 and the end is 10, the progress of this state is 50%
#         end     State in which the progress has terminated.
#         width   --
#         fill    String to use for "filled" used to represent the progress
#         blank   String to use for "filled" used to represent remaining space.
#         format  Format
#         incremental
#     """
#     def __init__(self, start=0, end=10, width=12, fill='=', blank='.', format='[%(fill)s>%(blank)s] %(progress)s%%', incremental=True):
#         super(ProgressBar, self).__init__()
# 
#         self.start = start
#         self.end = end
#         self.width = width
#         self.fill = fill
#         self.blank = blank
#         self.progress = float(self.start)
#         self.format = format
#         self.progress = 0
#         self.incremental = incremental
#         self.reset()
# 
#     def __add__(self, increment):
#         if self.end > self.progress + increment:
#             self.progress += increment
#         else:
#             self.progress = float(self.end)
#         return self
# 
#     def set(self, prog):
#         self.progress = prog
# 
#     def __sub__(self, decrement):
#         if self.start < self.progress - decrement:
#             self.progress -= decrement
#         else:
#             self.progress = float(self.start)
#         return self
# 
#     def __str__(self):
#         cur_width = int(self.progress / self.end * self.width)
#         fill = cur_width * self.fill
#         blank = (self.width - cur_width) * self.blank
#         percentage = int(self.progress / self.end * 100)
#         return self.format % {'fill': fill, 'blank': blank, 'progress': percentage}
# 
#     __repr__ = __str__
# 
#     def reset(self):
#         """Resets the current progress to the start point"""
#         self.progress = float(self.start)
#         return self
# 
# Path: lib/exception.py
# class DataException(Exception):
# 
#     def __init__(self, message):
#         # Call the base class constructor with the parameters it needs
#         super(DataException, self).__init__(message)
#         self.returncode = 2
#         logg = Logger('DataException')
#         logg.error(message)
# 
# class MissingException(Exception):
# 
#     def __init__(self, message):
#         # Call the base class constructor with the parameters it needs
#         super(MissingException, self).__init__(message)
#         self.returncode = 4
# 
#         logg = Logger('MissingException')
#         logg.error(message)
# 
# class NetworkException(Exception):
# 
#     def __init__(self, message):
#         # Call the base class constructor with the parameters it needs
#         super(NetworkException, self).__init__(message)
#         self.returncode = 3
# 
#         logg = Logger('NetworkException')
#         logg.error(message)


import lib.env
import sqlite3
import argparse
import os
import sys
import traceback
import json
from lib.loghelper import Logger
from lib.sitkaAPI import APIGet
from lib.progressbar import ProgressBar
from lib.exception import DataException, MissingException, NetworkException
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print '\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix),'\r'
    # sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percent, '%', suffix))
    # sys.stdout.flush()  # As suggested by Rom Ruben

    # Print New Line on Complete
    if iteration == total:
        print()

def main():
    # parse command line options
    parser = argparse.ArgumentParser()
    parser.add_argument('workbench', help='Workbench database path', type=argparse.FileType('r'))
    parser.add_argument('outputfolder', help='Path to output folder', type=str)
    args = parser.parse_args()

    if not os.path.isdir(args.outputfolder):
        os.makedirs(args.outputfolder)

    # Initiate the log file

# Path: lib/loghelper.py
# class Logger():
#     """
#     Think of this class like a light interface
#     """
# 
#     def __init__(self, method=""):
#         self.instance = _LoggerSingleton()
#         self.method = method
# 
#     def setup(self, **kwargs):
#         self.instance.setup(**kwargs)
# 
#     def print_(self, message, **kwargs):
#         self.instance.logprint(message, **kwargs)
# 
#     def debug(self, *args):
#         """
#         This works a little differently. You can basically throw anything you want into it.
#         :param message:
#         :return:
#         """
#         msgarr =  []
#         for arg in args:
#             if type(arg) is str:
#                 msgarr.append(arg)
#             else:
#                 msgarr.append(pformat(arg))
#         finalmessage = '\n'.join(msgarr).replace('\n', '\n              ')
#         self.instance.logprint(finalmessage, self.method, "debug")
# 
#     def destroy(self):
#         self.instance = None
#         self.method = None
# 
#     def info(self, message):
#         self.instance.logprint(message, self.method, "info")
# 
#     def error(self, message, exception=None):
#         self.instance.logprint(message, self.method, "error", exception)
# 
#     def warning(self, message, exception=None):
#         self.instance.logprint(message, self.method, "warning", exception)
# 
# Path: lib/sitkaAPI.py
# def APIGet(url, absolute=False):
#     """
#     GET Wrapper around APIGet
#     :param url:
#     :param absolute:
#     :return:
#     """
#     log = Logger("APIGet")
#     #log.info("Making Call: GET {}".format(url))
#     return APICall(url, absolute, method=requests.get)
# 
# Path: lib/progressbar.py
# class ProgressBar(object):
#     """ProgressBar class holds the options of the progress bar.
#     The options are:
#         start   State from which start the progress. For example, if start is
#                 5 and the end is 10, the progress of this state is 50%
#         end     State in which the progress has terminated.
#         width   --
#         fill    String to use for "filled" used to represent the progress
#         blank   String to use for "filled" used to represent remaining space.
#         format  Format
#         incremental
#     """
#     def __init__(self, start=0, end=10, width=12, fill='=', blank='.', format='[%(fill)s>%(blank)s] %(progress)s%%', incremental=True):
#         super(ProgressBar, self).__init__()
# 
#         self.start = start
#         self.end = end
#         self.width = width
#         self.fill = fill
#         self.blank = blank
#         self.progress = float(self.start)
#         self.format = format
#         self.progress = 0
#         self.incremental = incremental
#         self.reset()
# 
#     def __add__(self, increment):
#         if self.end > self.progress + increment:
#             self.progress += increment
#         else:
#             self.progress = float(self.end)
#         return self
# 
#     def set(self, prog):
#         self.progress = prog
# 
#     def __sub__(self, decrement):
#         if self.start < self.progress - decrement:
#             self.progress -= decrement
#         else:
#             self.progress = float(self.start)
#         return self
# 
#     def __str__(self):
#         cur_width = int(self.progress / self.end * self.width)
#         fill = cur_width * self.fill
#         blank = (self.width - cur_width) * self.blank
#         percentage = int(self.progress / self.end * 100)
#         return self.format % {'fill': fill, 'blank': blank, 'progress': percentage}
# 
#     __repr__ = __str__
# 
#     def reset(self):
#         """Resets the current progress to the start point"""
#         self.progress = float(self.start)
#         return self
# 
# Path: lib/exception.py
# class DataException(Exception):
# 
#     def __init__(self, message):
#         # Call the base class constructor with the parameters it needs
#         super(DataException, self).__init__(message)
#         self.returncode = 2
#         logg = Logger('DataException')
#         logg.error(message)
# 
# class MissingException(Exception):
# 
#     def __init__(self, message):
#         # Call the base class constructor with the parameters it needs
#         super(MissingException, self).__init__(message)
#         self.returncode = 4
# 
#         logg = Logger('MissingException')
#         logg.error(message)
# 
# class NetworkException(Exception):
# 
#     def __init__(self, message):
#         # Call the base class constructor with the parameters it needs
#         super(NetworkException, self).__init__(message)
#         self.returncode = 3
# 
#         logg = Logger('NetworkException')
#         logg.error(message)


# Path: scripts/measurement_downloader.py
import lib.env
import sqlite3
import argparse
import os
import sys
import traceback
import json
from lib.loghelper import Logger
from lib.sitkaAPI import APIGet
from lib.progressbar import ProgressBar
from lib.exception import DataException, MissingException, NetworkException

        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print '\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix),'\r'
    # sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percent, '%', suffix))
    # sys.stdout.flush()  # As suggested by Rom Ruben

    # Print New Line on Complete
    if iteration == total:
        print()

def main():
    # parse command line options
    parser = argparse.ArgumentParser()
    parser.add_argument('workbench', help='Workbench database path', type=argparse.FileType('r'))
    parser.add_argument('outputfolder', help='Path to output folder', type=str)
    args = parser.parse_args()

    if not os.path.isdir(args.outputfolder):
        os.makedirs(args.outputfolder)

    # Initiate the log file

    logg = Logger("Measurement Downloader")