:- module(user_prov,
	  [write_graph_csv/0,
	   user_match/2,
	   list_user_tags/0]).

:- use_module(library(semweb/rdf_db)).
:- use_module(library(video_annotation)).


create_user_graph(Video, UserRelations) :-
	findall(r(User2,User1),
		(   user_match(Video, _Tag-Users),
		    enum_user_relations(Users, _-User1, _-User2),
		    User1 \== User2
		),
		UserRelations).

enum_user_relations([User1|Users], User1, User2) :-
	member(User2, Users).
enum_user_relations([_|Users], User1, User2) :-
	enum_user_relations(Users, User1, User2).


write_graph_csv :-
	tell('user_graph.csv'),
	findall(r(User1,User2),
		(   annotated_video(Video),
		    create_user_graph(Video, UserRelations),
		    member(r(User1,User2), UserRelations)
		),
		Relations0),
	sort(Relations0, Relations),
	forall(member(r(U1,U2), Relations),
	       (   rdf_global_id(_:UN1, U1),
		   rdf_global_id(_:UN2, U2),
		   format('~w,~w~n',[UN1,UN2])
	       )),
	told.

annotated_video(Video) :-
	rdf(Video,rdf:type,pprime:'Video'),
	once(rdf(Video,pprime:hasAnnotation,_)).

user_match(Video, Tag-Users) :-
	video_annotations(Video,As,[interval(10)]),
	member(annotation(Tag,_S,_E,Entries,_Score),As),
	length(Entries,N),
	N>1,
	findall(Time-User,
		(member(i(Entry,Time),Entries),
		 rdf(Entry,pprime:creator,User)
		), Users).


list_user_tags :-
	user_tags(PlayerTags),
	format_user_tags(PlayerTags).

user_tags(PlayerTags2) :-
	findall(Player-tag(Tag,Score),
		(rdf(TagEntry, pprime:creator, Player),
		 rdf(TagEntry,rdf:value,literal(Tag)),
		 rdf(TagEntry,pprime:score,literal(Score))
		),
		PlayerTags),
	keysort(PlayerTags,PlayerTags1),
	group_pairs_by_key(PlayerTags1,PlayerTags2).

format_user_tags(PlayerTags) :-
	forall(member(P-Tags,PlayerTags),
	       (   format('~w,',[P]),
		   format_tags(Tags))).

format_tags([]).
format_tags([Tag]) :-
	format('~w~n~n',Tag).
format_tags([Tag|Tags]) :-
	format('~w,',[Tag]),
	format_tags(Tags).