# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Chapter4Modified2.py
# Created by Silas Toms
# 2014 04 23
# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy
import csv


arcpy.env.overwriteOutput =True

Bus_Stops = r"C:\Projects\SanFrancisco.gdb\SanFrancisco\Bus_Stops"
CensusBlocks2010 = r"C:\Projects\SanFrancisco.gdb\SanFrancisco\CensusBlocks2010"
Inbound71 = r"C:\Projects\SanFrancisco.gdb\Chapter4Results\Inbound71"
Inbound71_400ft_buffer = r"C:\Projects\SanFrancisco.gdb\Chapter4Results\Inbound71_400ft_buffer"
Intersect71Census = r"C:\Projects\SanFrancisco.gdb\Chapter4Results\Intersect71Census"
bufferDist = 400
bufferUnit = "Feet"
lineNames = [('71 IB', 'Ferry Plaza'),('71 OB','48th Avenue')]
sqlTemplate = "NAME = '{0}' AND BUS_SIGNAG = '{1}'"
intersected = [Inbound71_400ft_buffer, CensusBlocks2010]
dataKey = 'NAME','STOPID'
fields = 'HOUSING10','POP10'
csvname = r'C:\Projects\Output\Averages.csv'


def formatSQLMultiple(dataList, sqlTemplate, operator=" OR "):
    'a function to generate a SQL statement'
    sql = ''
    for count, data in enumerate(dataList):
        if count != len(dataList)-1:
            sql += sqlTemplate.format(*data) + operator
        else:
            sql += sqlTemplate.format(*data)
    return sql


def formatIntersect(features):
    'a function to generate an intersect string'
    formatString = ''
    for count, feature in enumerate(features):
        if count != len(features)-1:
            formatString += feature + " #;"
        else:
            formatString += feature + " #"
    return formatString



def createResultDic(resultFC, key, values):
    dataDictionary = {}
    fields = []
    if type(key) == type((1,2)) or type(key) == type([1,2]):
        fields.extend(key)
        length = len(key)
    else:
        fields = [key]
        length = 1
    fields.extend(values)
    with arcpy.da.SearchCursor(resultFC, fields) as cursor:
        for row in cursor:
            busStopID = row[:length]
            data = row[length:]
            if busStopID not in dataDictionary.keys():

                dataDictionary[busStopID] = {}

            for counter,field in enumerate(values):
                if field not in dataDictionary[busStopID].keys():
                    dataDictionary[busStopID][field] = [data[counter]]
                else:
                    dataDictionary[busStopID][field].append(data[counter])
    
    return dataDictionary

def createCSV(data, csvname, mode ='ab'):
    with open(csvname, mode) as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',')
        csvwriter.writerow(data)

 
sql = formatSQLMultiple(lineNames, sqlTemplate)
 
print 'Process: Select'
arcpy.Select_analysis(Bus_Stops, 
                      Inbound71, 
                      sql)
     
print 'Process: Buffer'
arcpy.Buffer_analysis(Inbound71, 
                      Inbound71_400ft_buffer, 
                      "{0} {1}".format(bufferDist, bufferUnit), 
                      "FULL", "ROUND", "NONE", "")
 
iString = formatIntersect(intersected)
print iString
  
print 'Process: Intersect'
arcpy.Intersect_analysis(iString, 
                          Intersect71Census, "ALL", "", "INPUT")


print 'Process Results'
dictionary = createResultDic(Intersect71Census, dataKey, fields)


print 'Create CSV'
header = [dataKey]
for field in fields:
    header.append(field)
createCSV(header,csvname, 'wb' )


for counter, busStop in enumerate(dictionary.keys()):
    datakeys  = dictionary[busStop]
    averages = [busStop]

    for key in datakeys:
        data = datakeys[key]
        average = sum(data)/len(data)
        averages.append(average)
    createCSV(averages,csvname)

print "Data Analysis Complete"
