#import "MovieView.h"
#import "MovieApp.h"
#import <appkit/NXImage.h>
#import <appkit/nextstd.h>
#import <appkit/Panel.h>
#import <appkit/Window.h>
#import <objc/List.h>
#import <streams/streams.h>

@implementation MovieView

/* creates a new MovieView instance */
+ newPath:(const char *)thePath Width:(int)w Height:(int)h NumFrames:(int)nf
{
	self = [super new];
	path = malloc(strlen(thePath));
	strcpy(path, thePath);
	width = w;
	height = h;
	currentFrame = 0;
	numFrames = nf;
	frames = calloc(numFrames, sizeof(id));
	return self;
}

/* show a frame, load it if necessary */
- showFrameNumber:(int)frameNumber
{
	NXStream       *theStream;
	NXPoint         zeroPoint = {0, 0};
	char            tempPath[128];

	if (frames[frameNumber] == NULL) {
		strcpy(tempPath, path);
		if(filetype == 1) sprintf(&tempPath[strlen(tempPath)], "/%d.tiff", frameNumber);
		if(filetype == 2) sprintf(&tempPath[strlen(tempPath)], "/%d.eps", frameNumber);
		if(filetype == 0){
			NXRunAlertPanel("Error","Unsupported file type!","OK",NULL,NULL);
			[window close];
			return self;
		}
		frames[frameNumber] = [[NXImage alloc] initFromFile:tempPath];
		if (frames[frameNumber] == NULL) {
			NXRunAlertPanel("Error", "Frame %d not found.",
					"OK", NULL, NULL, frameNumber);
			[window close];
			return self;
		}
	}
	currentFrame = frameNumber;
	[self lockFocus];
	[frames[currentFrame] composite:NX_COPY toPoint:&zeroPoint];
	[self unlockFocus];
	return self;
}

/* respond to inquiries */
- (int)numFrames
{ return numFrames; }
- (int)currentFrame
{ return currentFrame; }

/* clean up */
- free
{
	int             i;
	for (i = 0; i < numFrames; i++)
		if (frames[i])
			[frames[i] free];
	free(frames);
	free(path);
	return[super free];
}

@end
