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

import arcpy
bufferDist = 400
mxdPath = r'C:\Projects\MXDs\Chapter9\MapDocument1.mxd'
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:
        stopPointGeometry = row[0]
        stopBuffer = stopPointGeometry.buffer(bufferDist)
        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
