/***
@author 8boomgaa & 8njemz
@date   2010/02/24 10:59
@descr
*/

:-consult('utils/number.pl').
:-consult('client_interface.pl').
:-consult('predicate_whitelist.pl').
:-dynamic(myID/1).

/**
@form	start_client
@descr	starts client with localhost and port found in 'utils/number.pl'
*/
start_client:-
	portnumber(P),
	start_client(localhost,P).

/**
@form	start_client(+Port)
@descr	starts client on localhost with given port
*/
start_client(Port) :- start_client(localhost,Port).

/**
@form	start_client(+IP,+Port)
@constraints
@ground IP
@unrestricted Port
@descr	starts client with given IP and port. if no port given, takes port in 'utils/number.pl', if no IP given, takes localhost
*/
start_client(IP,P):-
	( var(P) -> portnumber(P) ; true),
	( var(IP) -> IP = localhost ; true),
	new(@s, socket(tuple(IP,P))),
	send(@s, input_message, message(@prolog, server_request, @arg1)),
        send(@s, connect).

/**
@form	exit_connection
@descr	sends a disconnect request to server and frees the socket
*/
exit_connection:-
	( myID(ID) -> send(disconnect_request(ID)) ; true ),
	( free(@s) ; true ),
	retractall(myID(_)),
	write_ln('disconnected from server').

/**
@form   server_request(+Message)
@descr  checks if the requested predicate is in the whitelist and executes it
*/
server_request(Msg):-
	get(Msg, value, Chars),
	atom_to_term(Chars,Cmd,_),
        Cmd =.. [Name|_],
	wl(Name),!, %checks whitelist for predicate-name
	write_ln(Cmd),
	Cmd,!.
server_request(Msg):- % case 'assert(myID(ID))'
	get(Msg, value, Chars),
	atom_to_term(Chars,Cmd,_),
	Cmd =.. [assert,Command],
	Command =.. [Name|_],
	wl(Name),!,
	write_ln(Cmd),
	do_assert(Cmd).
%	Cmd,
%	number_of_clients(Num),
%	( Num > 0 -> reduce_number_player, send(connection_request(ID)) ; true ),!.
server_request(Msg):-
	get(Msg, value, Chars),
	atom_to_term(Chars,Cmd,_),
	write(Cmd),
        write_ln(' -> not allowed').

/**
@form	send(+Predicate)
@descr	sends a predicate to server. if server knows it, it'll be used
*/
send(Predicate):-
        term_to_atom(Predicate,Atom),
        send(@s, append_line, Atom).
%Known commands:
%nick_chosen(+ID,+Nick)
%chat(+ID,+Message)
