:- use_module(library(sockets)).

go(Port) :- 
	write('this is server!!!'), nl,
	
	socket_server_open(Port, My_Socket),
	write('Server started\n'),
	
	asserta(n(0)),
	repeat,
	player_accept(My_Socket),
	repeat,
	server_loop,
	socket_server_close(My_Socket),
	write('Server stopped\n').	
	
player_accept(_My_Socket) :-
	n(2), !.
	
player_accept(My_Socket) :-
	n(N),
	socket_server_accept(My_Socket, Client1, Stream1, [type(text)]),
	N1 is N + 1,
	retract(n(N)),
	asserta(n(N1)),
	write('Client accepted: '), write(Client1), nl,
	format(Stream1, 'connected.~n', []),
	asserta(client(Stream1)),
	fail.
	
server_loop :-	
	findall(Stream, client(Stream), Client_List),
	Client_List = [Stream1, Stream2],

	% 각 client 들에게서 묵, 찌, 빠 중에 하나를 내도록 한다. 
	format(Stream1, 'select.~n',[]),
	flush_output(Stream1),
	format(Stream2, 'select.~n',[]),
	flush_output(Stream2),
	read(Stream1, Request1),
	read(Stream2, Request2), 
	write('Selected M/Z/B from client: '), write(Request1), nl,
	write('Selected M/Z/B from client: '), write(Request2), nl,
	
	% 상대 client가 이전에 무엇을 내었는 지를 전해 준다.
	flush_output(Stream1),
	format(Stream1, 'result-~w.~n', ['zzi']),
	flush_output(Stream1),
	flush_output(Stream2),
	format(Stream2, 'result-~w.~n', ['bba']), 
	flush_output(Stream2),
	
	% client 종료
	flush_output(Stream1),
	format(Stream1, 'end.~n', []),
	flush_output(Stream1),
	flush_output(Stream2),
	format(Stream2, 'end.~n', []), 
	flush_output(Stream2),!
	.
	
