'''
Name: avi_record_tools.py

Overview: 

Description:
    
Notes:

Author: Doug Crane
        Oct, 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_record import *
from avi_schema 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', \
        'TRUE', \
        'REMOVE_NULLS']
        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)
        processAllFeatures = arcpy.GetParameterAsText(1)
        toolType = arcpy.GetParameterAsText(2).strip().upper()

        # If calling from ArcMap then will be passed a feature
        # layer that may only have some features selected. Want
        # to make sure all features are processed if desired. This
        # will be the default for the tool.
        if processAllFeatures.upper() == 'FALSE':
            processAllFeatures = False
        else:
            processAllFeatures = True

        utilFC = srd_featureclass_info.SRD_FeatureClassInfo(fcPath)
        
        # If it is a feature layer it may only have a selected set
        # of records. Determine if all records should be processed
        # even if a subset is selected.
        if utilFC.isFeatureLayer():
            aviFL = fcPath
            if processAllFeatures:
                logChn.logMsg('\n*** All records will be processed')
                arcpy.SelectLayerByAttribute_management(aviFL, 'CLEAR_SELECTION')
            else:
                logChn.logMsg('\n*** Only selected records will be processed')
        else:
            aviFL = arcpy.MakeFeatureLayer_management(fcPath, 'avi_record_tools.fl')
        
        aviRec = AVI_Record(aviFL)
        aviSchemaObj = AVI_Schema()
        
        if toolType == 'SET_PROPER_CASE':
            aviRec.setProperCase()
        elif toolType == 'VALIDATE_DOMAINS':
            aviRec.validateDomains()
        elif toolType == 'REMOVE_BLANKS':
            aviRec.removeBlanks()
        elif toolType == 'REMOVE_NULLS':
            aviRec.removeNulls()
        elif toolType == 'CORE_DATA':
            aviRec.flagCoreData()
        elif toolType == 'ADD_AVI_FIELDS':
            aviSchemaObj.addAVIFields(fcPath)
        elif toolType == 'ADJUST_AVI_ATTRIBUTES':
            aviRec.adjustAttributes()
        elif toolType == 'PRIME_COV':
            aviRec.calcPrimeCov()
        elif toolType == 'VALIDATE_SCHEMA':
            errList = aviSchemaObj.validateFieldStructure(fcPath)
            if len(errList) > 0:
                for errMsg in errList:
                    logChn.logMsg(errMsg,2)
            else:
                logChn.logMsg('\n*** No Schema errors detected\n')
        else:
            SRD_Exception('Invalid Tool Type: %s' % toolType)
        
    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()
            
