from bottle import route, run, template, response
import urllib

#==============
# Persisting the graph to disk
#==============
@route('/cleargraph')
def cleargraph():
    graphFile = open("syntaxGraph.json", "w")
    print "opened graph file, which should have cleared it"
    graphFile.close()
    response.set_header('Access-Control-Allow-Origin', '*')

@route('/save1elem/<thejson>')
def save1elem(thejson):
    thejson = thejson.replace('%T', '\t')
    thejson = thejson.replace('%N', '\n')
    thejson = thejson.replace('%H', '\\')
    thejson = thejson.replace('%S', '/')
#    print thejson
    graphFile = open("syntaxGraph.json", "a")
    graphFile.write("%s\nseparator\n" % thejson)
    graphFile.close()
    response.set_header('Access-Control-Allow-Origin', '*')
    return "ACK"

#================
# Retrieving graph
#================

@route('/retrievegraph')
def retrieveGraph():
	graphFile = open("syntaxGraph.json", "r")
	returnjson = graphFile.read()
	response.set_header('Access-Control-Allow-Origin', '*')
	graphFile.close()
	return returnjson

#================

#Deprecated -- at first, tried open via "start" URL, then write, then close
# here..  but issues in async mode.  So now, just "start" clears the file
# then write opens in append mode, writes, and closes right away.
#So no longer need the "end" URL
@route('/endsavinggraph')
def endsavinggraph():
	global graphFile
	response.set_header('Access-Control-Allow-Origin', '*')
	graphFile.close()
	return 'ACK'

#Deprecated -- start and end retrieve are deprecated
@route('/startretrievinggraph')
def startretrievinggraph():
	global graphFile
	graphFile = open("syntaxGraph.json", "r")
	response.set_header('Access-Control-Allow-Origin', '*')
	return 'ACK'

@route('/endretrievinggraph')
def endretrievinggraph():
	global graphFile
	response.set_header('Access-Control-Allow-Origin', '*')
	graphFile.close()
	return 'ACK'

#================

run(host='localhost', port=8080)

