'''
Name: avi_spatial_audit.py

Overview: Performs the spatial audit of AVI feature class.

Description:
    This script will perform the spatial audit of an AVI feature
    class to ensure it meets requirements of AVI 2.1. Where an
    error is detected it is written to an audit feature class
    if it is a spatial error. The name of the FGDB containing
    audit error feature classes is the same as the FGDB containing
    the AVI feature class being audited but with a '_audit' appended
    to the end of its name. A log file is also generated that is
    the same name as the audit error FGDB but with a .log extension.
    
Notes:

Author: Doug Crane
        Sept, 2009

Modifications:

'''

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_audit import *

DEBUG = 0
#--------------------------------------------------------------------------
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'D:\testData\AVI\AVI_REC.gdb\avi_out']
        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)

        #-------------------------------------------------------------
        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

        fcPath = arcpy.GetParameterAsText(0)

        repairGeometry = arcpy.GetParameterAsText(1)
        if repairGeometry.upper() == 'TRUE':
            repairGeometry = True
        else:
            repairGeometry = False
            
        chkFields = arcpy.GetParameterAsText(2)
        if chkFields.upper() == 'TRUE':
            chkFields = True
        else:
            chkFields = False
        
        chkOverlap = arcpy.GetParameterAsText(3)
        if chkOverlap.upper() == 'TRUE':
            chkOverlap = True
        else:
            chkOverlap = False

        chkGaps = arcpy.GetParameterAsText(4)
        if chkGaps.upper() == 'TRUE':
            chkGaps = True
        else:
            chkGaps = False

        chkNeighbors = arcpy.GetParameterAsText(5)
        if chkNeighbors.upper() == 'TRUE':
            chkNeighbors = True
        else:
            chkNeighbors = False

        chkMultiParts = arcpy.GetParameterAsText(6)
        if chkMultiParts.upper() == 'TRUE':
            chkMultiParts = True
        else:
            chkMultiParts = False

        chkDupPolynums = arcpy.GetParameterAsText(7)
        if chkDupPolynums.upper() == 'TRUE':
            chkDupPolynums = True
        else:
            chkDupPolynums = False

        utilFCObj = srd_featureclass_info.SRD_FeatureClassInfo(fcPath)
        fullFCPath = utilFCObj.fullPath

        # We want to make sure that no selection set has been
        # made on layer to ensure all features are audited.
##        if utilFCObj.isFeatureLayer():
##            arcpy.SelectLayerByAttribute_management(fcPath, 'CLEAR_SELECTION')
            
        # Spatial errors identified through the audit process
        # will be written to FGDB based on the name of the FGDB
        # that contains the feature class being evaluated. The
        # audit FGDB will be same name as FGDB with the feature
        # class being audited but with an '_audit' appended to
        # end.
        srcGdbPath = utilFCObj.getFGDBPath()
        srcGdbDir = utilFCObj.getParentDir()
        srcGdbName = os.path.basename(srcGdbPath)
        name,ext = os.path.splitext(srcGdbName)

        gdbName = '%s_audit.gdb' % name
        gdbPath = os.path.join(srcGdbDir, gdbName)
        if arcpy.Exists(gdbPath):
            logChn.logMsg('\n*** %s already exists, will recreate' % gdbName)
            arcpy.Delete_management(gdbPath)

        logFileName = '%s.log' % name
        logFilePath = os.path.join(srcGdbDir, logFileName)
        logChn.logMsg('***\n*** Audit results will be logged to:\n %s\n***' % logFilePath)

        logChn.logMsg('\n***\n *** Spatial errors will be written to:\n %s\n***' % gdbPath)
        aviAuditObj = AVI_Audit(gdbPath)
        aviAuditObj.auditAll(fcPath, 
                             repairGeometry, 
                             chkFields, 
                             chkOverlap, 
                             chkGaps, 
                             chkNeighbors, 
                             chkMultiParts, 
                             chkDupPolynums, 
                             False)
            
    except SRD_Exception as e:
        logChn.logError(e)
        logChn.logError(srd_misc.exceptionDetails(sys.exc_info()[2]))
    except Exception as e:
        logChn.logError(e)
        logChn.logError(srd_misc.exceptionDetails(sys.exc_info()[2]))
    else:
        logChn.logMsg('\n*** %s completed normally\n' % sys.argv[0])
    finally:
        arcpy.ResetEnvironments()
