# ---------------------------------------------------------------------------
# Chapter9_3_CURRENT.py
# Created by Silas Toms
# 2014 09 23
# ---------------------------------------------------------------------------

import arcpy
bufferDist = 400
mxdPath = 'CURRENT'
mxdObject = arcpy.mapping.MapDocument(mxdPath)
dataFrame = arcpy.mapping.ListDataFrames(mxdObject, 
                                         "Layers")[0]
layersList = arcpy.mapping.ListLayers(mxdObject,
                                      "",dataFrame)
busStops = layersList[0]
censusBlocks = layersList[3]
defQuery = "NAME = '71 IB' AND BUS_SIGNAG = 'Ferry Plaza'"
busStops.definitionQuery = defQuery
idList =[]
with arcpy.da.SearchCursor(busStops,['SHAPE@',
                                     'STOPID',
                                     'NAME',
                                     'BUS_SIGNAG',
                                     'OID@',
                                     'SHAPE@XY']) as cursor:    
    for row in cursor:
        busQuery = 'OBJECTID = {0}'.format(row[-1])
        busStops.definitionQuery = busQuery
        
        stopPointGeometry = row[0]
        stopBuffer = stopPointGeometry.buffer(bufferDist)
        arcpy.MakeFeatureLayer_management(stopBuffer, "400 Foot Buffer")
        arcpy.SelectLayerByLocation_management(censusBlocks,
                                               'intersect',
                                               stopBuffer,
                                               "",
                                               "NEW_SELECTION")
        blockList = []
        with arcpy.da.SearchCursor(censusBlocks,
                                   ['OID@']) as bcursor:
            for brow in bcursor:
                blockList.append(brow[0])
        newQuery = 'OBJECTID IN ('
        for COUNTER, oid in enumerate(blockList):
            if COUNTER < len(blockList)-1:
                newQuery += str(oid) + ','
            else:
                newQuery += str(oid)+ ')'
        print newQuery
        censusBlocks.definitionQuery = newQuery
        dataFrame.extent = censusBlocks.getExtent()
        arcpy.SelectLayerByAttribute_management(censusBlocks,
                                               "CLEAR_SELECTION")
        print dataFrame.scale
        dataFrame.scale = dataFrame.scale * 1.1
        arcpy.RefreshActiveView()
        print dataFrame.scale
        censusBlocks.definitionQuery = ''
        break
#        censusBlocks.definitionQuery = ''
        
