# ---------------------------------------------------------------------------
# Chapter10_2.py
# Created by Silas Toms
# 2014 10 23
# ---------------------------------------------------------------------------


import arcpy, os
from common.useful import nonIntersect, generatePoints,formatSQLMultiple, createCSV

arcpy.env.overwriteOutput = True

busStops = r'C:\Projects\SanFrancisco.gdb\SanFrancisco\Bus_Stops'
parks = r'C:\Projects\SanFrancisco.gdb\SanFrancisco\RPD_Parks'
censusBlocks = r'C:\Projects\SanFrancisco.gdb\SanFrancisco\CensusBlocks2010'
csvName = r'C:\Projects\Output\Chapter10Analysis.csv'

headers = 'Line Name','Stop ID', 'Total Population Served'
createCSV(headers,csvName,mode='wb')

arcpy.MakeFeatureLayer_management(censusBlocks,'census_lyr')
parkGeometries = arcpy.CopyFeatures_management(parks,arcpy.Geometry())
parkUnion = parkGeometries[0]
for park in parkGeometries[1:]:
    parkUnion = parkUnion.union(park)


sql = "NAME = '71 IB' AND BUS_SIGNAG = 'Ferry Plaza'"
with arcpy.da.SearchCursor(busStops, ['NAME','STOPID','SHAPE@'],sql) as cursor:
    for row in cursor:
        lineName = row[0]
        stopID = row[1]
        stop = row[2]
        busBuf = stop.buffer(400)
        arcpy.SelectLayerByLocation_management("census_lyr","intersect",busBuf, '','NEW_SELECTION')
        totalPopulation = 0
        with arcpy.da.SearchCursor("census_lyr", ['SHAPE@','POP10','BLOCKID10']) as ncursor:
            for nrow in ncursor:
                block = nrow[0]
                checkedBlock = nonIntersect(block,parkUnion)
                blockName = nrow[2]
                population = nrow[1]
                if population != 0:
                    points = generatePoints("PopPoints",population, checkedBlock)
                    pointsGeom = arcpy.CopyFeatures_management(points,arcpy.Geometry())
                    pointsUnion = pointsGeom[0]
                    for point in pointsGeom[1:]:
                        pointsUnion = pointsUnion.union(point)
                    pointsInBuffer = busBuf.intersect(pointsUnion,1)
                    intersectedPoints = pointsInBuffer.pointCount
                    totalPopulation += intersectedPoints
        data = lineName, stopID,totalPopulation
        print 'data written', data
        createCSV(data, csvName)
os.startfile(csvName)
