# ---------------------------------------------------------------------------
# Chapter12_3.py
# Created by Silas Toms
# 2014 12 25
# ---------------------------------------------------------------------------


import arcpy

folderPath = arcpy.GetParameterAsText(0)
gdbName = arcpy.GetParameterAsText(1)
if gdbName.find('.') == -1:
    gdbName += ".gdb"
arcpy.CreateFileGDB_management(folderPath, gdbName)
arcpy.AddMessage("File Geodatabase Complete")

spatialReference = arcpy.SpatialReference(2227)
fileGDB = r"{0}\{1}".format(folderPath,gdbName)
featureDataset = arcpy.GetParameterAsText(2)
arcpy.CreateFeatureDataset_management(fileGDB, featureDataset, spatialReference)
arcpy.AddMessage("Feature Dataset Complete")

featureClass = arcpy.GetParameterAsText(3)
geometryType = "POLYGON"
featurePath = r"{0}\{1}".format(fileGDB,featureDataset)
arcpy.CreateFeatureclass_management(featurePath, featureClass, geometryType)
arcpy.AddMessage("Feature Class Complete")

fieldName = "STOPID"
fieldAlias = "Bus Stop Identifier"
fieldType = "LONG"
fieldPrecision = 9
featureClassPath = r"{0}\{1}".format(featurePath,featureClass)
arcpy.AddField_management(featureClassPath, fieldName, fieldType, fieldPrecision, "", "", fieldAlias)
arcpy.AddMessage("Field {0} Added".format(fieldName))

fieldName2 = "AVEPOP"
fieldAlias2 = "Average Census Population"
fieldType2 = "FLOAT"
featureClassPath = r"{0}\{1}".format(featurePath,featureClass)
arcpy.AddField_management(featureClassPath, fieldName2, fieldType2, "", "", "", fieldAlias2)
arcpy.AddMessage("Field {0} Added".format(fieldName2))

busStops = arcpy.GetParameterAsText(4)
censusBlocks2010 = arcpy.GetParameterAsText(5)
busStopField = arcpy.GetParameterAsText(6)
censusBlockPopField = arcpy.GetParameterAsText(7)
sql = arcpy.GetParameterAsText(8)

arcpy.AddMessage("Beginning Analysis")
insertCursor = arcpy.da.InsertCursor(featureClassPath, ['SHAPE@',fieldName,fieldName2])
arcpy.MakeFeatureLayer_management(censusBlocks2010, "census_lyr")

with arcpy.da.SearchCursor(busStops, ['SHAPE@', busStopField],sql) as cursor:
    for row in cursor:
        stop = row[0]
        stopID = row[1]
        busBuffer = stop.buffer(400)
        arcpy.SelectLayerByLocation_management("census_lyr","intersect",busBuffer, '','NEW_SELECTION')
        censusShapes = []
        censusPopList = []
        with arcpy.da.SearchCursor("census_lyr", ['SHAPE@',censusBlockPopField]) as ncursor:
            for nrow in ncursor:
                censusShapes.append(nrow[0])
                censusPopList.append(nrow[1])

        censusUnion = censusShapes[0]
        for block in censusShapes[1:]:
            censusUnion = censusUnion.union(block)
        
        censusPop = sum(censusPopList)/len(censusPopList)
        finalData = (censusUnion,stopID, censusPop)
        insertCursor.insertRow(finalData)
        
        
arcpy.AddMessage("Analysis Complete")
