from bottle import route, run, template, response

graphFile = None

@route('/')
def index():
    return '<b>Hello</b>!'

@route('/<name>')
@route('/hello/<name>')
def nameroute(name):
    return template('<b>Hello {{name}}</b>!', name=name)

@route('/savejson/<thejson>')
def savejson(thejson):
	text_file = open("syntaxGraph.json", "w")
	text_file.write("%s" % thejson)
	text_file.close()
	print "hello"
	response.set_header('Access-Control-Allow-Origin', '*')
#	return 'Got JSON!'
#	return template('Got JSON! {{printjson}}</b>!', printjson = thejson)

@route('/getjson')
def getjson():
	text_file = open("syntaxGraph.json", "r")
	returnjson = text_file.read()
	text_file.close()
	response.set_header('Access-Control-Allow-Origin', '*')
	return returnjson

#===============
@route('/startsavinggraph')
def startsavinggraph():
	global graphFile
	graphFile = open("syntaxGraph.json", "w")
	response.set_header('Access-Control-Allow-Origin', '*')

@route('/save1elem/<thejson>')
def save1elem(thejson):
	global graphFile
	graphFile.write("%s\n" % thejson)
	response.set_header('Access-Control-Allow-Origin', '*')

@route('/endsavinggraph')
def endsavinggraph():
	global graphFile
	response.set_header('Access-Control-Allow-Origin', '*')
	graphFile.close()

#================

@route('/startretrievinggraph')
def startretrievinggraph():
	global graphFile
	graphFile = open("syntaxGraph.json", "r")
	response.set_header('Access-Control-Allow-Origin', '*')

@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()

run(host='localhost', port=8080)
