# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Chapter4Modified1.py
# Created by Silas Toms
# 2014 05 05
# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy
import csv


# Local variables:
Bus_Stops = r"C:\Projects\SanFrancisco.gdb\SanFrancisco\Bus_Stops"
CensusBlocks2010 = r"C:\Projects\SanFrancisco.gdb\SanFrancisco\CensusBlocks2010"
Inbound71 = r"C:\Projects\SanFrancisco.gdb\Chapter3Results\Inbound71"
Inbound71_400ft_buffer = r"C:\Projects\SanFrancisco.gdb\Chapter3Results\Inbound71_400ft_buffer"
Intersect71Census = r"C:\Projects\SanFrancisco.gdb\Chapter3Results\Intersect71Census"
bufferDist = 400
lineName = '71 IB'
busSignage = 'Ferry Plaza'
def selectBufferIntersect(selectIn,selectOut,bufferOut,intersectIn,
                          intersectOut, bufferDist,lineName, busSignage ):
    arcpy.Select_analysis(selectIn, 
                          selectOut, 
                          "NAME = '{0}' AND BUS_SIGNAG = '{1}'".format(lineName, busSignage))
    arcpy.Buffer_analysis(selectOut, 
                          bufferOut, 
                          "{0} Feet".format(bufferDist), 
                          "FULL", "ROUND", "NONE", "")
    arcpy.Intersect_analysis("{0} #;{1} #".format(bufferOut,intersectIn), 
                             intersectOut, "ALL", "", "INPUT")
    return intersectOut

def createResultDic(resultFC):
    dataDictionary = {}
    
    with arcpy.da.SearchCursor(resultFC, 
                               ["STOPID","POP10"]) as cursor:
        for row in cursor:
            busStopID = row[0]
            pop10 = row[1]
            if busStopID not in dataDictionary.keys():
                dataDictionary[busStopID] = [pop10]
            else:
                dataDictionary[busStopID].append(pop10)
    return dataDictionary

def createCSV(dictionary, csvname):
    with open(csvname, 'wb') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',')
        for busStopID in dictionary.keys():
            popList = dictionary[busStopID]
            averagePop = sum(popList)/len(popList)
            data = [busStopID, averagePop]
            csvwriter.writerow(data)


analysisResult = selectBufferIntersect(Bus_Stops,Inbound71, Inbound71_400ft_buffer,CensusBlocks2010,Intersect71Census, bufferDist,lineName, busSignage )
dictionary = createResultDic(analysisResult)
createCSV(dictionary,r'C:\Projects\Output\Averages.csv')


print "Data Analysis Complete"
