def recommended_users(request):
	userUri = URIRef(request.user.get_profile().uri)
	
	friends = graph.query("""SELECT ?u WHERE {
					?u smdb:isFriendsWith ?me .
					}""", initBindings={'me': userUri})

	res = graph.query("""SELECT ?u ?f WHERE {
					?u rdf:type smdb:SMDBUser .
					?u smdb:hasSeen ?m .
					?me smdb:hasSeen ?m .
					OPTIONAL{ ?me smdb:isFriendsWith ?f . ?u smdb:isFriendsWith ?f } .
					FILTER( ?u != ?me) .
					}""", initBindings={'me': userUri})
					

	res = [ (SMDBUser(u), f) for (u, f) in res if u and u not in friends]
	
	sorted_res = sort_by_count(res, [0], 1)
	sorted_res = sorted_res[:4]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, friend, score)
	
	#for r in sorted_res: print r
	
	return sorted_res
def seen_by_friends(request):
	
	userUri = URIRef( request.user.get_profile().uri )
	
	seen_by_me = graph.query("""SELECT ?m WHERE {
				?me smdb:hasSeen ?m .
				}""", initBindings={'me': userUri})
	
	res = graph.query("""SELECT ?m ?t ?f WHERE {
				?m rdf:type smdb:Movie .
				?m smdb:title ?t .
				?f smdb:hasSeen ?m .
				?f smdb:isFriendsWith ?me .
				}""", initBindings={'me': userUri})
	
	#pprint(res)
	
	res = [ (m, t, f) for (m, t, f) in res if m not in seen_by_me]
	
	sorted_res = sort_by_count(res, [0,1], 2)
	sorted_res = sorted_res[:5]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, friend, score)
	
	#pprint(sorted_res)
	
	return sorted_res
def popular_movies():
				
	res = graph.query("""SELECT ?m ?t ?u WHERE {
				?m rdf:type smdb:Movie .
				?m smdb:title ?t .
				OPTIONAL{ ?u smdb:hasSeen ?m . }
				}""", initBindings={})
	
	#pprint(res)
	
	sorted_res = sort_by_count(res, [0,1], 2)
	sorted_res = sorted_res[:5]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, score)
	
	#pprint(sorted_res)
	
	return sorted_res
def movies_of_the_year():
	# This is popular_movies filtered by the current year
	
	year = datetime.datetime.now().year
	
	res = graph.query("""SELECT ?m ?t ?u WHERE {
				?m rdf:type smdb:Movie .
				?m smdb:title ?t .
				?m smdb:releaseDate "%s" .
				OPTIONAL{ ?u smdb:hasSeen ?m . }
				}""" % Literal(year), initBindings={})
	
	#pprint(res)
	
	sorted_res = sort_by_count(res, [0,1], 2)
	sorted_res = sorted_res[:5]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, score)
	
	#pprint(sorted_res)
	
	return sorted_res