with glfw3; use glfw3;
with gl; use gl;
with interfaces.c; use interfaces.c;

with sysutils;
with text_io; use text_io;
with ada.strings.unbounded; use ada.strings.unbounded;

package body sndloop is

--so far...
--this plays a soundfile zero to one times
--and stops as soon as the command is given.
--...I don't yet know how to make it repeat short sound loops as needed...

--NEED to detect when given pid has ended...so I can restart...OR...
--use known fileET as input...

task body sndtask is
	sndFileName: unbounded_string;
	usaplay : constant string := 
		"aplay --process-id-file apid.txt --nonblock --quiet ";
	skill : constant string := "/bin/kill ";
	ok: boolean;
	pidstr: string(1..99);
	last: natural;
	fid: file_type;
	tdur,tos,tod: gldouble;
	quit: boolean := false;
begin

outer:
loop

	select

		accept Start(name: string; dur: gldouble) do
			sndFileName := to_unbounded_string(name);
			tdur:=dur;
		end start;

		tod:=glfwGetTime;
		tos:=tod-2.0*tdur;

		sysutils.Shell( usaplay&to_string(sndFileName), Ok );
		delay 0.5; --give system 0.5sec to write file
		open(fid,in_file,"apid.txt");
		get_line(fid,pidstr,last);
		close(fid);
		put_line("running pid : "&pidstr(1..last));


		quit:=false;
		inner:
		loop
			exit inner when quit;
			select
				accept Stop do
					sysutils.Shell( skill&pidstr(1..last), Ok );
					put_line("killing : "&pidstr(1..last));
					quit:=true;
				end Stop;
			or
				delay 0.1;
			end select;

			tod:=glfwGetTime;

			if tod-tos>tdur then --reinitiate
				sysutils.Shell( usaplay&to_string(sndFileName), Ok );
				tos := tod;
				delay 0.5; --give system 0.5sec to write file
				open(fid,in_file,"apid.txt");
				get_line(fid,pidstr,last);
				close(fid);
				put_line("running pid : "&pidstr(1..last));
			end if;

		end loop inner;

	or
		terminate;
	end select;

end loop outer; --multiple restarts with water splash!

end sndtask;

end sndloop;

