//
//  Siundplayer.m
//  QTSound
//
//  Created by Ashley on 14/01/2007.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "Soundplayer.h"

@implementation Soundplayer

- (id) initWithSounds:(NSArray *)sounds
{
	[super init];
	[self setSounds:sounds];
	_counter = 0;
	_delegate = nil;
	
	return self;
}

- (void) setSounds:(NSArray *)sounds
{
	[sounds retain];
	[_sounds release];
	_sounds = sounds;
}

- (NSArray *)sounds
{
	return _sounds;
}

- (void) setDelegate:(id)delegate
{
	if (![delegate respondsToSelector:@selector(soundDidEnd:)]) {
		NSLog(@"Soundplayer:- delegate doesn't respond to selector soundDidEnd");
		return;
	}
	_delegate = delegate;
}

- (id) delegate
{
	return _delegate;
}

- (int) counter
{
	return _counter;
}

- (void) incCounter
{
	_counter++;
}

- (void) setCounter:(int)counter
{
	_counter = counter;
}

- (void) play
{
	[self setCounter:0];
	[self retain];
	[self nextSound:nil];

}

- (void) nextSound:(NSNotification *)sender
{
	NSNotificationCenter *centre = [NSNotificationCenter defaultCenter];
	int counter = [self counter];
	if (counter>0) {
		[[NSNotificationCenter defaultCenter] removeObserver:self];
	}
	
	if (counter<[[self sounds] count]) {
		NSLog(@"nextSound: playing counter = %d", counter);
		QTMovie *sound = [[self sounds] objectAtIndex:counter];
		
		[centre addObserver:self
				selector:@selector(nextSound:)
				name:QTMovieDidEndNotification
				object:sound]; 

		[sound gotoBeginning];
		[sound play];

		[self incCounter];
	} else {
		NSLog(@"nextSound: stopping _counter = %d", counter);
		[[self delegate] soundDidEnd:self];
		[self release];
	}
}

- (void) dealloc
{
	NSLog(@"Deallocating SoundPlayer");
	[_sounds release];
	[super dealloc];
}

@end
