/*
** Datatype Sound Player
*/

#include "include/config.h"

#include <proto/exec.h>
#include <proto/datatypes.h>
#include <proto/dtclass.h>
#include <clib/datatypes_protos.h>
#include <clib/alib_protos.h>
#include <datatypes/datatypes.h>
#include <datatypes/datatypesclass.h>
#include <datatypes/soundclass.h>

#include "include/thread.h"

void __asm __saveds snd_player(void);


void snd_play(char *fname)
{
	if (!fname) return;
	th_spawn(NULL, "Amster sound player", snd_player, 0, fname);
}


void __asm __saveds snd_player(void)
{
	thread t;
	struct Library *DosBase;
	struct Library *DataTypesBase;
	Object *sample;
	struct dtTrigger trigger;
	long ssig, tsig;

	t = thr_init();
	if (!t) return;
	tsig = (1L << (t->port->mp_SigBit));

	DosBase = OpenLibrary("dos.library", 36);
	if (!DosBase) {
		thr_exit(t, 1);
		return;
	}
	DataTypesBase = OpenLibrary("datatypes.library", 39);
	if (!DataTypesBase) {
		CloseLibrary(DosBase);
		thr_exit(t, 1);
		return;
	}

	ssig = AllocSignal(-1);
	if (ssig == -1) {
		CloseLibrary(DataTypesBase);
		CloseLibrary(DosBase);
		thr_exit(t, 1);
		return;
	}

	sample = NewDTObject((char*)t->data, DTA_GroupID, GID_SOUND, TAG_DONE);
	if (!sample) {
		FreeSignal(ssig);
		CloseLibrary(DataTypesBase);
		CloseLibrary(DosBase);
		thr_exit(t, 2);
		return;
	}

	SetDTAttrs(sample,NULL,NULL,SDTA_SignalBit,ssig,SDTA_SignalTask,t->task,TAG_DONE);

	trigger.MethodID = DTM_TRIGGER;
	trigger.dtt_GInfo = NULL;
	trigger.dtt_Function = STM_PLAY;
	trigger.dtt_Data = NULL;
	DoDTMethodA(sample, 0L, 0L, (Msg)&trigger);

	Wait((1L<<ssig)|tsig|SIGBREAKF_CTRL_C);

	DisposeDTObject(sample);
	FreeSignal(ssig);
	CloseLibrary(DataTypesBase);
	CloseLibrary(DosBase);
	thr_exit(t, 0);
}
