'''
Name: avi_remove_township.py

Purpose: Remove the township line that seperates AVI polygons.

Description:
    This class will remove the township line that seperates AVI
    polygons. Any polygons that are within 1 meter of a township line
    are extracted from the dataset. An attribute dissolve is then performed
    on these polygons. The resulting dissolved polygons will be written
    back into the original AVI to create the output AVI feature class.

    Note that while this method is better than using a general attribute
    dissolve to remove the township lines there may be cases where a
    polygon will be dissolved off the township line. This will happen where
    polygons cross a township but also touch at another location off the
    township boundary.

    To select AVI polygons that fall on the township border this method
    needs a township line feature class that is representitive of the one
    used in the AVI. If the AVI townships are not the same as the township
    feature class used for selection then the results may not be acceptable.
    
Notes:
    Must have a feature class representing the township lines that were
    used to partition the AVI into townships. This feature class must be
    contained in the same directory as the script and be named: 
    township_line_97.gdb and contain the line feature class township
    
Author: Doug Crane, Feb, 2011

Modifications:

'''

import os
import sys
import pdb
import inspect

import arcpy

# General SRD utilities that may be needed.
from srd.srd_exception import *
import srd.srd_logging as srd_logging
import srd.srd_misc as srd_misc
import srd.srd_temp_ws as srd_temp_ws
import srd.srd_recordset as srd_recordset

from avi_record import *

# Add any module variables you wish imported.
__all__ = ['AVI_RemoveTownship']

__author__ = 'Doug Crane'
__version__ = '1.0'

# ---------------------------------------------------------------
class AVI_RemoveTownship:
    '''
    '''


    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def __init__(self):
        '''

        Parameters:
        '''

        self._logChn = srd_logging.SRD_Log()
        
        # Determine location of the supporting Township dataset.
        scriptPath = inspect.getabsfile(self.__init__)
        scriptDir = os.path.dirname(scriptPath)
        twpGDBDir = scriptDir
        twpGDBPath = os.path.join(twpGDBDir, 'township_line_97.gdb')
        self.twpPath = os.path.join(twpGDBPath, 'township')
        
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def removeTownshipLine(self, srcAVI, outAVI, twpSelectionDistance, ignoreTPR, excludeCCArg=False):
        '''
        This method will remove the township line that seperates AVI
        polygons. Any polygons that are within 1 meter of a township line
        are extracted from the dataset. An attribute dissolve is then performed
        on these polygons. The resulting dissolved polygons will be written
        back into the original AVI to create the output AVI feature class.

        Note that while this method is better than using a general attribute
        dissolve to remove the township lines there may be cases where a
        polygon will be dissolved off the township line. This will happen where
        polygons cross a township but also touch at another location off the
        township boundary.

        To select AVI polygons that fall on the township border this method
        needs a township line feature class that is representitive of the one
        used in the AVI. If the AVI townships are not the same as the township
        feature class used for selection then the results may not be acceptable.
        
        Parameters:
            srcAVI - source AVI to remove township border from

            outAVI - resulting AVI to create.

            ignoreTPR - if set to True then the TPR will not be considered
                        when determining if attribues are same. In many cases
                        the only difference accross township lines is that the
                        TPR is not the same. Setting this to True will ensure
                        proper removal of the township border.

            excludeCCArg - if set to True then any polygons with a CC modifier
                           will not be considered for dissolve. This retains orignal
                           CC polygons.
        '''

        tmpFGDB = srd_temp_ws.SRD_TempWS('tmp_ws')

        # Make copy of the source AVI that will become output.
        self._logChn.logMsg('\n*** Copying source AVI polygons...')
        tmpOutFC = os.path.join(tmpFGDB.FGDBPath, 'src_avi')
        arcpy.MultipartToSinglepart_management(srcAVI, tmpOutFC)

        # Select all the polygons that are along a township border.
        self._logChn.logMsg('\n*** Selecting AVI polygons that fall on Township line...')
        selFL = 'bdySel_fl'
        arcpy.MakeFeatureLayer_management(tmpOutFC, selFL)
        arcpy.SelectLayerByLocation_management(selFL, 'WITHIN_A_DISTANCE', self.twpPath, twpSelectionDistance)

        selCnt = int(arcpy.GetCount_management(selFL).getOutput(0))

        # Remove overlapping duplicates using centroid information.
        if selCnt < 1:
            raise SRD_Exception('No AVI polygons selected by Township lines')
        else:
            self._logChn.logMsg('\n*** %s Boundary polygons selected...' % selCnt)
            
        # Copy the selected features to another feature class for
        # dissolving.
        
        tmpBdyFC = os.path.join(tmpFGDB.FGDBPath, 'bdy_polys')
        arcpy.CopyFeatures_management(selFL, tmpBdyFC)

        # Delete the copied polygons since we will later replace them
        # with the dissolved version.
        arcpy.DeleteFeatures_management(selFL)
        
        self._logChn.logMsg('\n*** Dissolving boundary polygons based on AVI attributes...')

        tmpDissolveFC = os.path.join(tmpFGDB.FGDBPath, 'dissolve_polys')

        aviRec = AVI_Record(tmpBdyFC)
        aviRec.dissolveByAttributeKey(tmpDissolveFC, ignoreTPR, excludeCCArg)

        # Append the dissolved polygons back into the original source AVI.
        self._logChn.logMsg('\n*** Integrating dissolved AVI into source...')
        arcpy.Append_management(tmpDissolveFC, tmpOutFC, 'NO_TEST')

        self._logChn.logMsg('\n*** Generating final AVI...')
        arcpy.MultipartToSinglepart_management(tmpOutFC, outAVI)

        tmpFGDB.deleteAllTempWS('tmp_ws')
        
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
if __name__ == '__main__':

    srcAVIArg = r'X:\prjs\blueridgeConversionFeb2011\township_test.gdb\BRL_AVI'
    outAVIArg = r'X:\prjs\blueridgeConversionFeb2011\township_test.gdb\BRL_AVI_notwp'
    twpSelDistArg = 5
    
    ignoreTPRArg = True
    excludeCCArg = True
    
    twpObj = AVI_RemoveTownship()

    twpObj.removeTownshipLine(srcAVIArg, outAVIArg, twpSelDistArg, ignoreTPRArg, excludeCCArg)

