'''
Name: avi_attribute_qc_tool.py

Overview: Performs the attribute audit of AVI feature class.

Description:
    
Notes:

Author: Doug Crane
        Sept, 2009

Modifications:

'''

logChn = None

import pdb
import os
import sys

import arcpy

from srd.srd_exception import *
import srd.srd_logging as srd_logging
import srd.srd_misc as srd_misc
import srd.srd_featureclass_info as srd_featureclass_info
from avi_attribute_qc import *

DEBUG = 0
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def writeLog():

    # Must have both the audit and informational tables to run.
    tablesExist = True
    if not arcpy.Exists(auditObj.auditTablePath):
        logChn.logMsg('\n***\n*** No audit table found for selected feature class, must first run attribute audit before trying to generate report.\n***')
        tablesExist = False

    if not arcpy.Exists(auditObj.infoTablePath):
        logChn.logMsg('\n***\n*** No information table found for selected feature class, must first run attribute audit before trying to generate report.\n***')
        tablesExist = False

    if tablesExist:                
        auditObj.writeAuditReport(reportPathArg, errorsOnly, True)

#--------------------------------------------------------------------------
if __name__ == '__main__':

    arcpy.env.overwriteOutput = True
    # If using geographic features then may be best to modify these.
    arcpy.env.XYTolerance = .001
    arcpy.env.XYResolution = .0001
    arcpy.gp.logHistory = False

    if DEBUG:
        # Modify arguments to simulate those passed from toolbox.
        # You will have to modify these based on your scripts requirements.
        sys.argv = [sys.argv[0], \
        r'X:\prjs\S10\dec23_2009\avi_89135.gdb\avi\avi']
        print('\n***\n*** IN DEBUG MODE\n***')
        arcpy.AddMessage('\n***\n*** IN DEBUG MODE\n***')
        
    try:

        logFilePath = srd_misc.getLogFilePath(sys.argv[0])
        logChn = srd_logging.SRD_Log(logFilePath)

        #-------------------------------------------------------------
        # Set the log file.
        if logFilePath:
            try:
                # Parameters to tool will be written to log file in case of problems.
                params = arcpy.GetParameterInfo()
                hdrList = ['Arguments:']
                for param in params:
                    hdrList.append('Name: %s, Type: %s, Value: %s' % (param.name, param.parameterType, param.value))
                logChn.stampHeader(hdrList)
                arcpy.AddMessage('\n*** Log information will be written to: %s\n' % logFilePath)
                logChn.stampHeader(hdrList)
                arcpy.AddMessage('\n*** Log information will be written to: %s\n' % logFilePath)
            except:
                pass

        ##==============================
        ## Modify parameters as needed.
        fcPathArg = arcpy.GetParameterAsText(0)
        errorsOnlyArg = arcpy.GetParameterAsText(1)
        if errorsOnlyArg.upper() == 'TRUE':
            errorsOnly = True
        else:
            errorsOnly = False

        # ATT error report is same name as FGDB and in same directory.
        fcInfoObj = srd_featureclass_info.SRD_FeatureClassInfo(fcPathArg)
        gdbPath = fcInfoObj.getFGDBPath()
        if not gdbPath:
            raise SRD_Exception('Unable to obtain path to FGDB')

        gdbDir = os.path.dirname(gdbPath)
        gdbName,ext = os.path.splitext(os.path.basename(gdbPath))
        reportPathArg = os.path.join(gdbDir, '%s_att.log' % gdbName)
        arcpy.AddMessage('\n***\n*** Att Error Log: %s\n***' % reportPathArg)

        ##============================================================

        auditObj = AVI_AttributeAudit(fcPathArg)
        auditObj.auditAttributes()

        # No errors may have ben encountered.
        if errorsOnly:
            if auditObj.totalErrorCount < 1:
                logChn.logWarning('\n***\n*** No errors were detected, no error report generated\n***')
            else:
                writeLog()
        else:
            if auditObj.totalErrorCount < 1 and auditObj.totalWarningCount < 1:
                logChn.logWarning('\n***\n*** No errors or warningss were detected, no error report generated\n***')
            else:
                writeLog()
        
    except SRD_Exception as e:
        if logChn:
            logChn.logError(e)
            logChn.logError(srd_misc.exceptionDetails(sys.exc_info()[2]))
        else:
            arcpy.AddMessage(srd_misc.exceptionDetails(sys.exc_info()[2]))
    except Exception as e:
        if logChn:
            logChn.logError(e)
            logChn.logError(srd_misc.exceptionDetails(sys.exc_info()[2]))
        else:
            arcpy.AddMessage(srd_misc.exceptionDetails(sys.exc_info()[2]))
    else:
        logChn.logMsg('\n*** %s completed normally\n' % sys.argv[0])
    finally:
        arcpy.ResetEnvironments()
        if logChn:
            logChn.closeLog()
        
