# Google Earth Program

# This program takes a list of tweets and makes a KML file of pins.

# Import Statements
import csv
import re

# CONSTANTS: these variables never change
TWEET_FILE = 'brown.out'

def getBrownTweets():
  ''' reads tweets & writes KML file
  INPUTS: none
  OUTPUTS: none'''

  tweetList = readTweets()
  print 'There are',len(tweetList),'tweets in this file.'
  writeKMLFile(tweetList,'BrownTweets.kml');

  return

def readTweets():
  '''Reads Tweets and returns a list of tweets.
  INPUT: none
  OUTPUT: list of lists'''
  
  # open file (use csv reader)
  myFile = open(TWEET_FILE,'r')
  myCSVReader = csv.reader(myFile,delimiter=',',quotechar='"')

  # read lines from file and put in a list
  # after this loop, myCSVList will contain a list of tweets,
  # which are each 13-element lists.
  myCSVList = []
  skipCount = 0
  for row in myCSVReader: # iterator object that returns lists
    if float(row[5]) == 0.0 or float(row[6]) == 0.0 or len(row) != 13:
      #print 'skipping tweet',row
      skipCount = skipCount + 1
    else: # write tweet if it passes all filters.
      # replace invalid XML characters in name and tweet
      row[3] = re.sub('&','and',row[3])
      row[3] = re.sub('>',' ',row[3])
      row[3] = re.sub('<',' ',row[3])
      row[12] = re.sub('&','and',row[12])
      row[12] = re.sub('>',' ',row[12])
      row[12] = re.sub('<',' ',row[12])

      # finally, add tweet to list.
      myCSVList = myCSVList + [row]

  # done with file: close it
  myFile.close()

  print skipCount,'tweets have been skipped.'
  return myCSVList

def writeKMLFile(tweetList,filename):
  '''Writes a KML file of tweets.
  INPUTS: list of lists, output filename (string)
  OUTPUTS:  none'''

  outFile = open(filename,'w')

  outFile.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  outFile.write('<kml xmlns="http://www.opengis.net/kml/2.2">\n')
  outFile.write(' <Document>\n')

  for i in range(0,len(tweetList)):
    writeTweet(tweetList[i],outFile)
  
  outFile.write(' </Document>\n')
  outFile.write('</kml>\n')
  outFile.close()
  
  return

def writeTweet(tweet,outFile):
  '''Writes a single tweet to the output file
  INPUTS: tweet (list), outFile (file object)
  OUTPUTS: none'''

  placemarkString = '''   <Placemark>
     <name>''' + tweet[3] + '''</name>
     <description>''' + tweet[12]+ '''</description>
     <Style>
       <IconStyle>
         <scale>1.1</scale>
         <Icon>
           <href>http://maps.google.com/mapfiles/kml/pushpin/wht-pushpin.png</href>
         </Icon>
         <color>ff0000ff</color>
       </IconStyle>
     </Style>
     <Point>
       <coordinates>''' + tweet[6] + ''',''' + tweet[5] + ''',0</coordinates>
     </Point>
   </Placemark>'''

  outFile.write(placemarkString)
  outFile.write('\n')
  
  return
