# Path: lib/channelunits.py
# def createChannelUnitJSONFile(visitID, workbenchDB, jsonFilePath):
# 
#     dUnits = loadChannelUnitsFromSQLite(visitID, workbenchDB)
#     writeChannelUnitsToJSON(jsonFilePath, dUnits)
# 
# Path: tools/topometrics/topometrics.py
# def visitTopoMetrics(visitID, metricXMLPath, topoDataFolder, channelunitsfile, workbenchdb, channelUnitDefs):
# 
#     log = Logger('Metrics')
#     log.info("Topo topometrics for visit {0}".format(visitID))
# 
#     # Load the topo data object that specifies the full paths to each data layer
#     log.info("Loading topo data from {0}".format(topoDataFolder))
# 
#     topo = TopoData(topoDataFolder, visitID)
#     topo.loadlayers()
# 
#     # Load the channel unit information from the argument XML file
#     if channelunitsfile is not None:
#         channelUnitInfo = loadChannelUnitsFromJSON(channelunitsfile)
#     elif workbenchdb is not None:
#         channelUnitInfo = loadChannelUnitsFromSQLite(visitID, workbenchdb)
#     else:
#         channelUnitInfo = loadChannelUnitsFromAPI(visitID)
# 
#     # This is the dictionary for all topometrics to this visit. This will get written to XML when done.
#     visitMetrics = {}
# 
#     # Loop over all the channels defined in the topo data (wetted and bankfull)
#     for channelName, channel in topo.Channels.iteritems():
#         log.info("Processing topometrics for {0} channel".format(channelName.lower()))
# 
#         # Dictionary for the topometrics in this channel (wetted or bankfull)
#         dChannelMetrics = {}
# 
#         metrics_cl = CenterlineMetrics(channel.Centerline)
#         integrateMetricDictionary(dChannelMetrics, 'Centerline', metrics_cl.metrics)
# 
#         metrics_we = WaterExtentMetrics(channelName, channel.Extent, channel.Centerline, topo.Depth)
#         integrateMetricDictionary(dChannelMetrics, 'WaterExtent', metrics_we.metrics)
# 
#         metrics_cs = CrossSectionMetrics(channel.CrossSections, topo.Channels[channelName].Extent, topo.DEM, 0.1)
#         integrateMetricDictionary(dChannelMetrics, 'CrossSections', metrics_cs.metrics)
# 
#         metrics_i = IslandMetrics(channel.Islands)
#         integrateMetricDictionary(dChannelMetrics, 'Islands', metrics_i.metrics)
# 
#         # Put topometrics for this channel into the visit metric dictionary keyed by the channel (wetted or bankfull)
#         integrateMetricDictionary(visitMetrics, channelName, dChannelMetrics)
# 
#         log.info("{0} channel topometrics complete".format(channelName))
# 
#     metrics_thal = ThalwegMetrics(topo.Thalweg, topo.Depth, topo.WaterSurface, 0.1, visitMetrics)
#     integrateMetricDictionary(visitMetrics, 'Thalweg', metrics_thal.metrics)
# 
#     # Channel units creates four groupings of topometrics that are returned as a Tuple
#     cuResults = ChannelUnitMetrics(topo.ChannelUnits, topo.Thalweg, topo.Depth, visitMetrics, channelUnitInfo, channelUnitDefs)
#     integrateMetricList(visitMetrics, 'ChannelUnits', 'Unit', cuResults.metrics['resultsCU'])
#     integrateMetricDictionary(visitMetrics, 'ChannelUnitsTier1', cuResults.metrics['ResultsTier1'])
#     integrateMetricDictionary(visitMetrics, 'ChannelUnitsTier2', cuResults.metrics['ResultsTier2'])
#     integrateMetricDictionary(visitMetrics, 'ChannelUnitsSummary', cuResults.metrics['ResultsChannelSummary'])
# 
#     temp = RasterMetrics(topo.Depth)
#     integrateMetricDictionary(visitMetrics, 'WaterDepth', temp)
# 
#     temp = RasterMetrics(topo.DEM)
#     integrateMetricDictionary(visitMetrics, "DEM", temp)
# 
#     temp = RasterMetrics(topo.Detrended)
#     integrateMetricDictionary(visitMetrics, "Detrended", temp)
# 
#     # special bankfull metrics appending to existing dictionary entry
#     visitMetrics['Bankfull']['WaterExtent'].update(BankfullMetrics(topo.DEM, topo.Detrended, topo.TopoPoints))
# 
#     # Metric calculation complete. Write the topometrics to the XML file
#     writeMetricsToXML(visitMetrics, visitID, topoDataFolder, metricXMLPath, "TopoMetrics", __version__)
# 
#     log.info("Metric calculation complete for visit {0}".format(visitID))
#     return visitMetrics


import os
import argparse
import sys
from lib.channelunits import createChannelUnitJSONFile
from tools.topometrics.topometrics import visitTopoMetrics

def runSingleVisit(visitID, visitFolder, visitOutputFolder, workbenchDB, bVerbose):

    xmlFile = os.path.join(visitOutputFolder, "topometrics.xml")
    logFile = os.path.join(visitOutputFolder, "topometrics.log")
    chaFile = os.path.join(visitOutputFolder, "channelunits.json")

    createChannelUnitJSONFile(visitID, workbenchDB, chaFile)

    visitTopoMetrics(visitFolder, visitID, xmlFile, chaFile)

if __name__ == "__main__":

    # parse command line options
    parser = argparse.ArgumentParser()
    parser.add_argument('visitID', help='Visit ID')
    parser.add_argument('visitFolder', help='Visit folder containing Harold results')
    parser.add_argument('outputfolder', help='OUTPUT folder where visit results will be written')
    parser.add_argument('workbench', help='Path to Workbench SQLite database', type=argparse.FileType('r'))
    parser.add_argument('--verbose', help = 'Get more information in your logs.', action='store_true', default=False)

    args = parser.parse_args()

    if not args.visitID or not args.visitFolder or not args.outputfolder or not args.workbench:
        print "ERROR: Missing arguments"
        parser.print_help()
        exit(0)

    try:

# Path: lib/channelunits.py
# def createChannelUnitJSONFile(visitID, workbenchDB, jsonFilePath):
# 
#     dUnits = loadChannelUnitsFromSQLite(visitID, workbenchDB)
#     writeChannelUnitsToJSON(jsonFilePath, dUnits)
# 
# Path: tools/topometrics/topometrics.py
# def visitTopoMetrics(visitID, metricXMLPath, topoDataFolder, channelunitsfile, workbenchdb, channelUnitDefs):
# 
#     log = Logger('Metrics')
#     log.info("Topo topometrics for visit {0}".format(visitID))
# 
#     # Load the topo data object that specifies the full paths to each data layer
#     log.info("Loading topo data from {0}".format(topoDataFolder))
# 
#     topo = TopoData(topoDataFolder, visitID)
#     topo.loadlayers()
# 
#     # Load the channel unit information from the argument XML file
#     if channelunitsfile is not None:
#         channelUnitInfo = loadChannelUnitsFromJSON(channelunitsfile)
#     elif workbenchdb is not None:
#         channelUnitInfo = loadChannelUnitsFromSQLite(visitID, workbenchdb)
#     else:
#         channelUnitInfo = loadChannelUnitsFromAPI(visitID)
# 
#     # This is the dictionary for all topometrics to this visit. This will get written to XML when done.
#     visitMetrics = {}
# 
#     # Loop over all the channels defined in the topo data (wetted and bankfull)
#     for channelName, channel in topo.Channels.iteritems():
#         log.info("Processing topometrics for {0} channel".format(channelName.lower()))
# 
#         # Dictionary for the topometrics in this channel (wetted or bankfull)
#         dChannelMetrics = {}
# 
#         metrics_cl = CenterlineMetrics(channel.Centerline)
#         integrateMetricDictionary(dChannelMetrics, 'Centerline', metrics_cl.metrics)
# 
#         metrics_we = WaterExtentMetrics(channelName, channel.Extent, channel.Centerline, topo.Depth)
#         integrateMetricDictionary(dChannelMetrics, 'WaterExtent', metrics_we.metrics)
# 
#         metrics_cs = CrossSectionMetrics(channel.CrossSections, topo.Channels[channelName].Extent, topo.DEM, 0.1)
#         integrateMetricDictionary(dChannelMetrics, 'CrossSections', metrics_cs.metrics)
# 
#         metrics_i = IslandMetrics(channel.Islands)
#         integrateMetricDictionary(dChannelMetrics, 'Islands', metrics_i.metrics)
# 
#         # Put topometrics for this channel into the visit metric dictionary keyed by the channel (wetted or bankfull)
#         integrateMetricDictionary(visitMetrics, channelName, dChannelMetrics)
# 
#         log.info("{0} channel topometrics complete".format(channelName))
# 
#     metrics_thal = ThalwegMetrics(topo.Thalweg, topo.Depth, topo.WaterSurface, 0.1, visitMetrics)
#     integrateMetricDictionary(visitMetrics, 'Thalweg', metrics_thal.metrics)
# 
#     # Channel units creates four groupings of topometrics that are returned as a Tuple
#     cuResults = ChannelUnitMetrics(topo.ChannelUnits, topo.Thalweg, topo.Depth, visitMetrics, channelUnitInfo, channelUnitDefs)
#     integrateMetricList(visitMetrics, 'ChannelUnits', 'Unit', cuResults.metrics['resultsCU'])
#     integrateMetricDictionary(visitMetrics, 'ChannelUnitsTier1', cuResults.metrics['ResultsTier1'])
#     integrateMetricDictionary(visitMetrics, 'ChannelUnitsTier2', cuResults.metrics['ResultsTier2'])
#     integrateMetricDictionary(visitMetrics, 'ChannelUnitsSummary', cuResults.metrics['ResultsChannelSummary'])
# 
#     temp = RasterMetrics(topo.Depth)
#     integrateMetricDictionary(visitMetrics, 'WaterDepth', temp)
# 
#     temp = RasterMetrics(topo.DEM)
#     integrateMetricDictionary(visitMetrics, "DEM", temp)
# 
#     temp = RasterMetrics(topo.Detrended)
#     integrateMetricDictionary(visitMetrics, "Detrended", temp)
# 
#     # special bankfull metrics appending to existing dictionary entry
#     visitMetrics['Bankfull']['WaterExtent'].update(BankfullMetrics(topo.DEM, topo.Detrended, topo.TopoPoints))
# 
#     # Metric calculation complete. Write the topometrics to the XML file
#     writeMetricsToXML(visitMetrics, visitID, topoDataFolder, metricXMLPath, "TopoMetrics", __version__)
# 
#     log.info("Metric calculation complete for visit {0}".format(visitID))
#     return visitMetrics


# Path: test/topometrics/run_single_visit.py
import os
import argparse
import sys
from lib.channelunits import createChannelUnitJSONFile
from tools.topometrics.topometrics import visitTopoMetrics


def runSingleVisit(visitID, visitFolder, visitOutputFolder, workbenchDB, bVerbose):

    xmlFile = os.path.join(visitOutputFolder, "topometrics.xml")
    logFile = os.path.join(visitOutputFolder, "topometrics.log")
    chaFile = os.path.join(visitOutputFolder, "channelunits.json")

    createChannelUnitJSONFile(visitID, workbenchDB, chaFile)

    visitTopoMetrics(visitFolder, visitID, xmlFile, chaFile)

if __name__ == "__main__":

    # parse command line options
    parser = argparse.ArgumentParser()
    parser.add_argument('visitID', help='Visit ID')
    parser.add_argument('visitFolder', help='Visit folder containing Harold results')
    parser.add_argument('outputfolder', help='OUTPUT folder where visit results will be written')
    parser.add_argument('workbench', help='Path to Workbench SQLite database', type=argparse.FileType('r'))
    parser.add_argument('--verbose', help = 'Get more information in your logs.', action='store_true', default=False)

    args = parser.parse_args()

    if not args.visitID or not args.visitFolder or not args.outputfolder or not args.workbench:
        print "ERROR: Missing arguments"
        parser.print_help()
        exit(0)

    try:

        dMetrics = runSingleVisit(args.visitID, args.visitFolder, args.outputfolder, args.workbench.name, args.verbose)