# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Chapter5Modified2.py
# Created by Silas Toms
# 2014 05 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'
spatialReference = arcpy.SpatialReference(4326)

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 createCSV(data, csvname, mode ='ab'):
    with open(csvname, mode) as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',')
        csvwriter.writerow(data)

 
sql = formatSQLMultiple(lineNames, sqlTemplate)

dataList = []
with arcpy.da.SearchCursor(Bus_Stops, ['NAME','STOPID','SHAPE@XY'], sql,spatialReference) as cursor:
    for row in cursor:
        linename = row[0]
        stopid = row[1]
        locationX = row[2][0]
        locationY = row[2][1]
        data = linename, stopid, locationX, locationY
        if data not in dataList:
            dataList.append(data)

csvname = "C:\Projects\Output\StationLocations.csv"
headers = 'Bus Line Name','Bus Stop ID', 'X','Y'
createCSV(headers, csvname, 'wb')     
for data in dataList:  
    print data
    createCSV(data, csvname)
         
 
 
 
 
