from bottle import route, run, template, response
import urllib

graphFile = None

#==============

@route('/startsavinggraph')
def startsavinggraph():
    global graphFile
    graphFile = open("syntaxGraph.json", "w")
    print "opened graph file "
    print "Name of the file: ", graphFile.name
    print "Closed or not : ", graphFile.closed
    print "Opening mode : ", graphFile.mode
    print "Softspace flag : ", graphFile.softspace
    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
	global graphFile
	graphFile.write("%s\nend elem\n" % thejson)
	response.set_header('Access-Control-Allow-Origin', '*')

@route('/endsavinggraph')
def endsavinggraph():
	global graphFile
	response.set_header('Access-Control-Allow-Origin', '*')
	graphFile.close()
	return 'ACK'

#================

@route('/startretrievinggraph')
def startretrievinggraph():
	global graphFile
	graphFile = open("syntaxGraph.json", "r")
	response.set_header('Access-Control-Allow-Origin', '*')
	return 'ACK'

@route('/get1elem')
def get1elem():
	global graphFile
	returnjson = graphFile.readline()
	response.set_header('Access-Control-Allow-Origin', '*')
	return returnjson

@route('/endretrievinggraph')
def endretrievinggraph():
	global graphFile
	response.set_header('Access-Control-Allow-Origin', '*')
	graphFile.close()
	return 'ACK'

#================

run(host='localhost', port=8080)

