/*
 *  LevelBGView.m
 *  fmod_rocks2010
 *
 *	Music and Code by Peter "pdx" Drescher.
 *  Copyright 2010 twittering machine. All rights reserved.
 
	Draws level backgrounds and random ship/rocks (for eye candy)
 *
 */
#import "LevelBGview.h"

#define SPRITE_SIZE 30

@implementation LevelBGview

- (id)initWithFrame:(NSRect)frame {
    if (![super initWithFrame:frame]) 
		return nil;
	
	srand ( time(NULL) );
	bundle = [NSBundle mainBundle];
	[self setLevelBG:1];
	shipRect.size.width = SPRITE_SIZE;
	shipRect.size.height = SPRITE_SIZE;
	rockRect.size.width = SPRITE_SIZE;
	rockRect.size.height = SPRITE_SIZE;
	return self;
}

- (void)dealloc
{
	[super dealloc];
}

- (void)drawRect:(NSRect)rect {
	NSRect bounds = [self bounds];

//	draw the level background
	[levelBG drawInRect:bounds
			   fromRect:NSZeroRect
			  operation:NSCompositeSourceOver
			   fraction:1.0];
	[levelBG release];

//	draw the ship
	shipName = [NSMutableString stringWithFormat:@"ID_ship_f%02d", ((rand() % 10)+1)];
	ship = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:shipName	ofType:@"png"]];
	shipRect.origin.x = rand() % 200;
	shipRect.origin.y = rand() % 100;
	[ship drawInRect:shipRect
			   fromRect:NSZeroRect
			  operation:NSCompositeSourceOver
			   fraction:1.0];
	[ship release];

//  draw a rock, making sure it doesn't overlap the ship
	rockName = [NSMutableString stringWithFormat:@"ID_rock_f%02d", ((rand() % 10)+1)];
	rock = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:rockName ofType:@"png"]];
	rockRect.origin.x = rand() % 230;
	rockRect.origin.y = rand() % 120;
	if (NSIntersectsRect(shipRect, rockRect)) {
		rockRect.origin.x += (SPRITE_SIZE * 2);
		if (rockRect.origin.x > bounds.origin.x) {
			rockRect.origin.x -= bounds.origin.x;
		}
	} 
	[rock drawInRect:rockRect
			fromRect:NSZeroRect
		   operation:NSCompositeSourceOver
			fraction:1.0];
	[rock release];

	
//  draw another rock, making sure it doesn't overlap the ship
	rockName = [NSMutableString stringWithFormat:@"ID_rock_f%02d", ((rand() % 10)+1)];
	rock = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:rockName ofType:@"png"]];
	rockRect.origin.x = rand() % 230;
	rockRect.origin.y = rand() % 120;
	if (NSIntersectsRect(shipRect, rockRect)) {
		rockRect.origin.x += (SPRITE_SIZE * 2);
		if (rockRect.origin.x > bounds.origin.x) {
			rockRect.origin.x -= bounds.origin.x;
		}
	} 
	[rock drawInRect:rockRect
			fromRect:NSZeroRect
		   operation:NSCompositeSourceOver
			fraction:1.0];
	[rock release];
}

- (void)setLevelBG:(int)level
{
	levelName = [NSMutableString stringWithFormat:@"ID_playfield_f%02d", level];
	levelBG = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:levelName ofType:@"jpg"]];
	[self setNeedsDisplay:YES];
}


@end
