/*
 * Play sounds from the command line.
 * R. Matthew Emerson <rme@thoughtstuff.com>
 * December 2006
 *
 * compile with cc -o sndplay -framework Cocoa sndplay.m
 */

#import <Cocoa/Cocoa.h>
#include <unistd.h>
#include <err.h>
#include <sys/stat.h>

BOOL shouldKeepRunning = YES;

@interface Delegate : NSObject
{
}
@end

@implementation Delegate
- (void)sound:(NSSound *)sound didFinishPlaying:(BOOL)flag
{
    shouldKeepRunning = NO;
}
@end

char *filename;
int rval;
Delegate *delegate;

void usage();
void play(char *absolute_path);
void playfiles(char *argv[]);

int main(int argc, char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int ch;

    delegate = [[Delegate alloc] init];

    while ((ch = getopt(argc, argv, "")) != -1)
	switch (ch) {
	default:
	    usage();
	}
    argv += optind;

    playfiles(argv);

    [delegate release];
    [pool release];
    exit(rval);
}

void usage()
{
    fprintf(stderr, "usage: sndplay [file ...]\n");
    exit(1);
}

void play(char *absolute_path)
{
    NSString *path = [NSString stringWithCString:absolute_path
			       encoding:NSUTF8StringEncoding];
    NSSound *sound = [[NSSound alloc] initWithContentsOfFile:path
				      byReference:YES];
    BOOL flag;

    shouldKeepRunning = YES;
    [sound setDelegate:delegate];
    flag = [sound play];
    if (flag == NO) {
	warnx("can't play file %s", absolute_path);
	rval = 1;
    } else {
	NSRunLoop *rl = [NSRunLoop currentRunLoop];
	
	while (shouldKeepRunning) {
	    [rl runMode:NSDefaultRunLoopMode
		beforeDate:[NSDate distantFuture]];
	    fprintf(stderr, ".");
	}
    }
    [sound release];
}

void playfiles(char *argv[])
{
    int i = 0;
    char *path;
    char resolved_path[PATH_MAX];

    while ((path = argv[i]) != NULL || i == 0) {
	if (path == NULL) {
	    filename = "/dev/stdin";
	} else {
	    filename = realpath(path, resolved_path);
	}
	if (filename == NULL) {
	    warn("%s", resolved_path);
	    rval = 1;
	} else {
	    struct stat sb;

	    if (stat(filename, &sb) == -1)
		warn("%s", filename);
	    else {
		printf("%s\n", basename(filename));
		play(filename);
	    }
	}
	if (path == NULL)
	    break;
	++i;
    }
}
