'''
The classes defined here have the purpose of converting a list of entries
from the database, generated by a particular query, into a file of a particular
format specified by the class to be used. 

A GeoJSON converter may be the only necessary class to be made for this purpose,
but any future classes made to convert the database into a file should follow
GeoJSONConverter's format in order to maintain modular interoperability.
'''

class GeoJSONConverter:
	def __init__(self):
		self.fileStream = open(self._generateFileName(),"w+")
	def __del__(self):
		self.fileStream.close()
	def convert(self, databaseEntries):
		self.fileStream.write('{\n\t"type": "FeatureCollection",\n\t"features": [')
		
		for entryIndex in range(0,len(databaseEntries),1):
			entry = databaseEntries[entryIndex]
			if entryIndex is not 0:
				self.fileStream.write(',')
			self.fileStream.write('{\n\t\t"type": "Feature",\n\t\t"geometry": {\n\t\t\t"type": "Point",\n\t\t\t"coordinates": ['+ str(entry[11])+', '+str(entry[12])+']\n')
			self.fileStream.write('\t\t},\n\t\t"properties": {\n')
			if entry[0] is not None:
				self.fileStream.write('\t\t\t"rest_name": "'+self._sanitizeInput(entry[0])+'"\n')
			if entry[1] is not None:
				self.fileStream.write('\t\t\t,"address": "')
				for i in range(1,4,1):
					if entry[i] is not None:
						self.fileStream.write(str(entry[i])+' ')
				self.fileStream.write('"\n')
			if entry[6] is not None:
				self.fileStream.write('\t\t\t,"rest_type": "'+entry[6]+'"\n')
			if entry[7] is not None:
				self.fileStream.write('\t\t\t,"rest_status": "'+entry[7]+'"\n')
			if entry[8] is not None:
				self.fileStream.write('\t\t\t,"last_inspection": "'+entry[8]+'"\n')			
			if entry[9] is not None:
				self.fileStream.write('\t\t\t,"avg_score": "'+str(entry[9])+'"\n')
			if entry[10] is not None:
				self.fileStream.write('\t\t\t,"last_score": "'+str(entry[10])+'"\n')
			if entry[13] is not None:
				self.fileStream.write('\t\t\t,"rest_id": "' + str(entry[13])+'"\n')
			self.fileStream.write('\t\t}\n\t}')
		self.fileStream.write(']\n}')		

	def _generateFileName(self):
		return "/home/blake/RestaurantMapper/reports/restinfo/restInfo.json"
	
	def _sanitizeInput(self, inputString):
		return ''.join(inputString.split('"'))

#NOTE
#These functions were written for other formats while testing. While they're functional in their own right,
#they aren't really necessary anymore, and don't follow the proper format to be interoperable. I still like
#to keep them around for reference and just in case.
'''
 #Converts the entire database with long and lat values into a kml file
 def convertToKML(self, kmlFile):
     print("Opening file " + kmlFile)
     kmlFileStream = open(kmlFile, "a+")
     print("Converting database to kml format")
     kmlFileStream.write('<?xml version="1.0" encoding="UTF-8"?>\n')
     kmlFileStream.write('<kml xmlns="http://www.opengis.net/kml/2.2">\n')
     queryString = "SELECT rest_name, street_address, city_section, street_name, city, zip_code, rest_type, rest_status, avg_score, longitude, latitude FROM restaurants WHERE longitude IS NOT NULL"
     print("Grabbing entries.")
     self.cursor.execute(queryString)
     queryResults = self.cursor.fetchall()
     for result in queryResults:
         if result[8] is not None and result[9] is not None:
             kmlFileStream.write('\t<Placemark>\n')
             kmlFileStream.write('\t\t<name>' + result[0] + '</name>\n')
             kmlFileStream.write('\t\t<description>\n\t\t\t')
             for i in range(1,5,1):
                 if result[i] is not None:
                     kmlFileStream.write(str(result[i])+' ')
             if result[6] is not None:
                 kmlFileStream.write('\n\t\t\tStatus: '+ result[6]+'\n')
             if result[7] is not None:
                 kmlFileStream.write('\t\t\tAverage Score: ' + str(result[7]) +'\n')
             kmlFileStream.write('\t\t</description>\n')
             kmlFileStream.write('\t\t<Point>\n')
             kmlFileStream.write('\t\t\t<coordinates>'+str(result[8])+','+str(result[9])+',0</coordinates>\n\t\t</Point>\n')
             kmlFileStream.write('\t</Placemark>\n')
         print(".",end='')
     kmlFileStream.write('</kml>')
     print('\nFinished conversion')
     
     kmlFileStream.close()
     
 def convertToGPX(self, gpxFile):
     print("Opening file " + gpxFile)
     gpxFileStream = open(gpxFile, "a+")
     print("Converting database to gpx format")
     gpxFileStream.write('<?xml version="1.0" encoding="UTF-8"?>\n')
     gpxFileStream.write('<gpx version="1.0">\n')
     queryString = "SELECT rest_name, street_address, city_section, street_name, city, zip_code, rest_type, rest_status, avg_score, longitude, latitude FROM restaurants WHERE longitude IS NOT NULL"
     print("Grabbing entries.")
     self.cursor.execute(queryString)
     queryResults = self.cursor.fetchall()
     for result in queryResults:
         if result[8] is not None and result[9] is not None:
             gpxFileStream.write('\t<wpt lat='+str(result[8])+' lon='+str(result[9])+'>\n')
             gpxFileStream.write('\t<name>' + result[0] + '</name>\n')
             gpxFileStream.write('\t\t<desc>\n\t\t\t')
             for i in range(1,5,1):
                 if result[i] is not None:
                     gpxFileStream.write(str(result[i])+' ')
             if result[6] is not None:
                 gpxFileStream.write('\n\t\t\tStatus: '+ result[6]+'\n')
             if result[7] is not None:
                 gpxFileStream.write('\t\t\tAverage Score: ' + str(result[7]) +'\n')
             gpxFileStream.write('\t\t</desc>\n')
             gpxFileStream.write('\t</wpt>\n')
         print(".",end='')
     gpxFileStream.write('</gpx>')
     print('\nFinished conversion')
     
     gpxFileStream.close()
     
'''     
