#!/usr/bin/python
#-*- coding: utf-8 -*-

import sys
import pyodbc
import cgi
import cgitb

server = 'tcp:digerati.aks.ac.kr'
	
EditStoryUrl = "./edit/editStory.py"
Story01Url = "./Story01.py"
Story02Url = "./Story02.py"
StoryNode01Url = "./StoryNode01.py"
CategoryUrl = "./Category.py"

StoryIcon="./icon/network2.png"
NetworkIcon = "./icon/network64.png"
reficon="./icon/outlink2.png"
GhostIcon="./icon/ghost.png"
EpisodeIcon="./icon/episode.png"

def sayMessage( errNo ):

	if( errNo == 1 ):
		message = 'Database is Not Connected!'
		icon = './icon/notConnected.png'
	else:
		if( errNo == 2 ):
			message = 'Data Set is Not Available!'
			icon = './icon/notAvailable.png'
		else:
			message = 'No Valid Semantic Data!'
			icon = './icon/notFound.png'

	print "			nodesArray.push({"
	print "				id: 'errMessage',"
	print "				label: '{0}',".format( message )
	print "				shape: 'image',"
	print "				image: '{0}',".format( icon )
	print "			});\n"	
	


def printNodes( nodelist, database, project, account, password, subject ):
	
	for item in nodelist:
		id = item['id']
		label = item['label']
		if label is not None:
			label = label.replace("_", " ")
		else:
			label = 'Label is Missing!'
		print "			nodesArray.push({"
		print "				id: '{0}',".format( id )	
		if( id == subject ):
			subjectClass = item['class']
			print "				label: ' {0} ',".format(label)	
			if( item['url'] != None ): #has infoUrl	
				print "				url: '{0}',".format(item['url'])		
				print "				title: '<img src=\"{0}\"/>',".format(reficon)	
			if( item['icon'] != None ): #has Icon
				iconUrl = item['icon']
				if( iconUrl[-3:] == 'jpg') :
					print "				shapeProperties: { useBorderWithImage:true  },"
					print "				borderWidth: 3,"
					print "				color: {border: 'silver'},"
					print "				size: 100,"
				else:
					print "				size: 40,"				
				print "				shape: 'image',"
				print "				image: '{0}'".format(item['icon'])
			else:
				if( len(label) > 14 ): 
					print "				shape: 'ellipse',"			
				else:
					print "				shape: 'circle',"
				print "				color: {background: 'silver', border: 'darkgrey'}"
		else:
			if( item['class'] == 'WebResource' ): #direct link	
				print "				label: '{0}',".format( label )				
				print "				url: '{0}',".format(item['url'])	
				print "				shape: 'circularImage',"
				print "				image: '{0}'".format(item['icon'])					
			else:
				print "				label: '{0}',".format( label )				
				print "				url: '{0}?db={1}&project={2}&account={3}&pwd={4}&key={5}',".format(Story01Url, database, project, account, password, id)	
				if( item['icon'] != None ): #has Icon	
					print "				title: '<img src=\"{0}\"/>',".format(item['icon'])			
					print "				shape: 'image',"
					print "				image: '{0}'".format(item['icon'])
				else:
					print "				shape: 'box',"
					print "				color: {background: 'white', border: 'green'}"
		print "			});\n"		
				
	
	#add depth level switch	
	print "			nodesArray.push({"
	print "				id: 'switch2',"
	print "				label: 'Semantic Data',"
	print "				url: '{0}?db={1}&project={2}&account={3}&pwd={4}&key={5}',".format(Story01Url, database, project, account, password, subject)
	print "				shape: 'circularImage',"
	print "				size: 40,"	
	print "				image: '{0}'".format( NetworkIcon )
	print "			});\n"	

def printLinks( edgelist, subject, account ):

	for item in edgelist:
		if item['attribute'] is not None:
			labelString = '{0} ({1})'.format(item['relation'], item['attribute'])	
		else:
			labelString = item['relation']
		print "			edgesArray.push({"
		print "				from: '{0}',".format(item['source'])
		print "				to: '{0}',".format(item['target'])
		print "				label: '{0}',".format( labelString )		
		print "				arrows: 'to'"
		print "			});\n"
		
	
def displayData( database, project, account, password, node ):

	nodeTable = project + 'Data'
	edgeTable = project + 'Links'
	storyTable = project + 'Story'
	
	try:
		db = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+account+';PWD='+ password)
	except:
		sayMessage( 1 )
		return
		
	################################
	# story03
	################################
		
	cur = db.cursor()
		
	#1st step: get contextual element nodes of the chosen episode

	command = "select distinct target as id from " + storyTable + " where source=N'" + node + "'" + "and relation='hasContextualElement'"

	try:	
		cur.execute(unicode(command, "utf-8"))
	except:
		cur.close()
		db.close()
		sayMessage( 2 )
		return
	
	uniquelist = []	
	count = 0
	
	for row in cur.fetchall():
		uniquelist.append( {row[0]} )
		count = count + 1
		
	if( count == 0 ):
		cur.close()
		db.close()
		sayMessage( 3 )
		return
	
	#2nd step: get all the links among the contextual nods

	# select L.source, L.target, L.relation, L.attribute from hanyangLinks as L
	# join hanyangStory as A on L.source=A.target
	# join hanyangStory as B on L.target=B.target
	# where A.source='E4-001' and A.relation='hasContextualElement'

	command1 = "select distinct L.source, L.target, L.relation, L.attribute from " + edgeTable + " as L "
	command2 = "join " + storyTable + " as A on L.source=A.target "
	command3 = "join " + storyTable + " as B on L.target=B.target "
	command4 = "where A.source='" + node + "' and A.relation='hasContextualElement' and B.source='" + node + "' and B.relation='hasContextualElement'"
	#command4 = "where A.source='" + node + "' and B.source='" + node + "'"
	
	command  = command1 + command2 + command3 + command4
	
	cur.execute(unicode(command, "utf-8"))
		
	edgelist = []
	
	for row in cur.fetchall():
		edgelist.append( {'source':row[0], 'target':row[1], 'relation':row[2], 'attribute':row[3]} )
		
	#3nd step: get the attributes of each node
	
	nodelist = []
		
	#cur = db.cursor()	
	for item in uniquelist:
		str1 = ''.join(str(e) for e in item)
		#print "	{0}".format( str1 )
		command = "select id, class, label, infoUrl, iconUrl from " + nodeTable + " where id=N'"
		command += str1
		command += "'"
		cur.execute(unicode(command, "utf-8"))
		#for row in cur.fetchall():
		#	nodelist.append( {'id':row[0], 'class':row[1], 'label':row[2], 'url':row[3], 'icon':row[4]} )
		
		row = cur.fetchone()
		if row:
			nodelist.append( {'id':row[0], 'class':row[1], 'label':row[2], 'url':row[3], 'icon':row[4]} )		
		else:
			str2 = '{0}: Not Exist!'.format( str1 )
			nodelist.append( {'id':str1, 'class':'Ghost', 'label':str2, 'url':None, 'icon':GhostIcon} )
			
	cur.close()
	db.close()
	
	printNodes( nodelist, database, project, account, password, node )
	printLinks( edgelist, node, account )

	
def displayNetwork(template, db, project, account, pwd, node):

	print 'Content-type: text/html'
	print
	f = open(template)
	while 1:
		line = f.readline()
		if not line: break
		if( '#YourData' == line.strip()):
			displayData( db, project, account, pwd, node )
		else:
			print line,
			
	f.close()
	

def main():

	reload(sys)
	sys.setdefaultencoding('utf8')
	cgitb.enable()

	form = cgi.FieldStorage()

	try:
		db = form.getvalue('db', '')
		project = form.getvalue('project', '')
		account = form.getvalue('account', 'guest')
		pwd = form.getvalue('pwd', 'guest')
		node = form.getvalue('key', '')
	except:
		return

	displayNetwork("templateSov.htm", db, project, account, pwd, node)
	

main()
