# 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 downloadUnzipTopo(visitID, unzipPath):
#     """
#     Download a topo zip file to a local path using a visitID
#     :param visitID:
#     :param zipFilePath:
#     :return:
#     """
#     tokenator = Tokenator()
#     log = Logger("downloadTopoZip")
# 
#     # First find the appropriate download URL
#     try:
#         topoFieldFolders = APIGet('visits/{}/fieldFolders/Topo'.format(visitID))
# 
#         log.debug("Getting visit file data")
#         file = next(file for file in topoFieldFolders['files'] if file['componentTypeID'] == 181)
#         downloadUrl = file['downloadUrl']
#     except Exception, e:
#         raise MissingException("ERROR: No TopoData.zip file found for visit".format(visitID))
# 
#     # Download the file to a temporary location
#     with NamedTemporaryFile() as f:
#         response = APIGet(downloadUrl, absolute=True)
#         f.write(response.content)
# 
#         log.debug("Downloaded file: {} to: {}".format(downloadUrl, f.name))
# 
#         # Now we have it. Unzip
#         with zipfile.ZipFile(f, 'r') as zip_ref:
#             log.debug("Unzipping file: {} to: {}".format(f.name, unzipPath))
#             zip_ref.extractall(unzipPath)
# 
#         # Return a folder where we can find a project.rs.xml (or not)
#         projpath = None
#         for root, subFolders, files in os.walk(unzipPath):
#             if "project.rs.xml" in files:
#                 projpath = root
# 
#     return file, projpath
# 
# 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/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: lib/metricxmloutput.py
# def writeMetricsToXML(dMetricsArg, visitID, sourceDir, xmlFilePath, modelEngineRootNode, modelVersion):
#     log = Logger(__name__)
# 
#     tree = ET.ElementTree(ET.Element(modelEngineRootNode))
# 
#     nodMeta = ET.SubElement(tree.getroot(), 'Meta')
# 
#     datetag = ET.SubElement(nodMeta, DATECREATEDFIELD)
#     datetag.text = datetime.datetime.now().isoformat()
# 
#     version = ET.SubElement(nodMeta, VERSIONFIELD)
#     version.text = modelVersion
# 
#     nodVisitID = ET.SubElement(nodMeta, 'VisitID')
#     nodVisitID.text = str(visitID)
# 
#     nodMetrics = ET.SubElement(tree.getroot(), 'Metrics')
#     _writeDictionaryToXML(nodMetrics, dMetricsArg)
# 
#     rough_string = ET.tostring(tree.getroot(), 'utf-8')
#     reparsed = xml.dom.minidom.parseString(rough_string)
#     pretty = reparsed.toprettyxml(indent="\t")
#     with open(xmlFilePath, "wb") as f:
#         f.write(pretty)
# 
#     log.info("Wrote metrics to file: {}".format(xmlFilePath))


import sys
import os
import lib.env
import argparse
import traceback
import os
import argparse
from lib.loghelper import Logger
from lib.sitkaAPI import downloadUnzipTopo, APIGet
from lib.exception import DataException, MissingException, NetworkException
from lib.metricxmloutput import writeMetricsToXML
from metriclib.auxMetrics import *
from metriclib.fishMetrics import *
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))




__version__ = "0.0.4"

def runAuxMetrics(xmlfile, outputDirectory, visit_id):
    log = Logger("Validation")

    # Make a big object we can pass around
    try:
        visit = APIGet("visits/{}".format(visit_id))
    except MissingException, e:

# 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 downloadUnzipTopo(visitID, unzipPath):
#     """
#     Download a topo zip file to a local path using a visitID
#     :param visitID:
#     :param zipFilePath:
#     :return:
#     """
#     tokenator = Tokenator()
#     log = Logger("downloadTopoZip")
# 
#     # First find the appropriate download URL
#     try:
#         topoFieldFolders = APIGet('visits/{}/fieldFolders/Topo'.format(visitID))
# 
#         log.debug("Getting visit file data")
#         file = next(file for file in topoFieldFolders['files'] if file['componentTypeID'] == 181)
#         downloadUrl = file['downloadUrl']
#     except Exception, e:
#         raise MissingException("ERROR: No TopoData.zip file found for visit".format(visitID))
# 
#     # Download the file to a temporary location
#     with NamedTemporaryFile() as f:
#         response = APIGet(downloadUrl, absolute=True)
#         f.write(response.content)
# 
#         log.debug("Downloaded file: {} to: {}".format(downloadUrl, f.name))
# 
#         # Now we have it. Unzip
#         with zipfile.ZipFile(f, 'r') as zip_ref:
#             log.debug("Unzipping file: {} to: {}".format(f.name, unzipPath))
#             zip_ref.extractall(unzipPath)
# 
#         # Return a folder where we can find a project.rs.xml (or not)
#         projpath = None
#         for root, subFolders, files in os.walk(unzipPath):
#             if "project.rs.xml" in files:
#                 projpath = root
# 
#     return file, projpath
# 
# 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/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: lib/metricxmloutput.py
# def writeMetricsToXML(dMetricsArg, visitID, sourceDir, xmlFilePath, modelEngineRootNode, modelVersion):
#     log = Logger(__name__)
# 
#     tree = ET.ElementTree(ET.Element(modelEngineRootNode))
# 
#     nodMeta = ET.SubElement(tree.getroot(), 'Meta')
# 
#     datetag = ET.SubElement(nodMeta, DATECREATEDFIELD)
#     datetag.text = datetime.datetime.now().isoformat()
# 
#     version = ET.SubElement(nodMeta, VERSIONFIELD)
#     version.text = modelVersion
# 
#     nodVisitID = ET.SubElement(nodMeta, 'VisitID')
#     nodVisitID.text = str(visitID)
# 
#     nodMetrics = ET.SubElement(tree.getroot(), 'Metrics')
#     _writeDictionaryToXML(nodMetrics, dMetricsArg)
# 
#     rough_string = ET.tostring(tree.getroot(), 'utf-8')
#     reparsed = xml.dom.minidom.parseString(rough_string)
#     pretty = reparsed.toprettyxml(indent="\t")
#     with open(xmlFilePath, "wb") as f:
#         f.write(pretty)
# 
#     log.info("Wrote metrics to file: {}".format(xmlFilePath))


# Path: tools/auxmetrics/auxmetrics.py
import sys
import os
import lib.env
import argparse
import traceback
import os
import argparse
from lib.loghelper import Logger
from lib.sitkaAPI import downloadUnzipTopo, APIGet
from lib.exception import DataException, MissingException, NetworkException
from lib.metricxmloutput import writeMetricsToXML
from metriclib.auxMetrics import *
from metriclib.fishMetrics import *

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))




__version__ = "0.0.4"

def runAuxMetrics(xmlfile, outputDirectory, visit_id):
    log = Logger("Validation")

    # Make a big object we can pass around
    try:
        visit = APIGet("visits/{}".format(visit_id))
    except MissingException, e:

        raise MissingException("Visit Not Found in API")