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

import arcpy
bufferDist = 400
pdfFolder = r'C:\Projects\PDFs\Chapter9\Map_{0}'
mxdPath = r'C:\Projects\MXDs\Chapter9\MapDocument1.mxd'
mxdObject = arcpy.mapping.MapDocument(mxdPath)
dataFrame = arcpy.mapping.ListDataFrames(mxdObject, 
                                         "Layers")[0]
elements = arcpy.mapping.ListLayoutElements(mxdObject)
for el in elements:
    if el.type =="TEXT_ELEMENT":
        if el.text == 'Title Element':
            titleText = el
        elif el.text == 'Subtitle Element':
            subTitleText = el            
layersList = arcpy.mapping.ListLayers(mxdObject,
                                      "",dataFrame)
busStops = layersList[0]
censusBlocks = layersList[3]
sql = "NAME = '71 IB' AND BUS_SIGNAG = 'Ferry Plaza'"
idList =[]
with arcpy.da.SearchCursor(busStops,['SHAPE@',
                                     'STOPID',
                                     'NAME',
                                     'BUS_SIGNAG',
                                     'OID@'],sql) as cursor:    
    for row in cursor:
        busQuery = 'OBJECTID = {0}'.format(row[-1])
        busStops.definitionQuery = busQuery
        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
        censusBlocks.definitionQuery = newQuery
        dataFrame.extent = censusBlocks.getExtent()
        arcpy.SelectLayerByAttribute_management(censusBlocks,
                                               "CLEAR_SELECTION")
        dataFrame.scale = dataFrame.scale * 1.1
        arcpy.RefreshActiveView()
        subTitleText.text = "Route {0}".format(row[2])
        titleText.text = "Bus Stop {0}".format(row[1])
        outPath  = pdfFolder.format( str(row[1])+ "_" + str(row[-2])) + '.pdf'
        print outPath
        arcpy.mapping.ExportToPDF(mxdObject,outPath)
        titleText.text = 'Title Element'
        subTitleText.text = 'Subtitle Element'
        censusBlocks.definitionQuery = ''