/*
        Copyright (c) 1996, NeXT Software, Inc.
        All rights reserved.

        You may freely copy, distribute and reuse the code in this example.
        NeXT disclaims any warranty of any kind, expressed or implied,
        as to its fitness for any particular use.
*/
#import "Studio.h"
#import "Talent.h"

@implementation Studio

- (NSDecimalNumber *)portfolioValue
{
    NSDecimal result = [[NSDecimalNumber zero] decimalValue];
    int i = [movies count];
    while( i-- ) {
        NSDecimalNumber *value = [[movies objectAtIndex:i] valueForKey:@"revenue"];     
        if(value) {
            NSDecimal total = [value decimalValue];
            NSDecimalAdd(&result, &result,  &total, NSRoundBankers);          
        }
    }
    return [NSDecimalNumber decimalNumberWithDecimal:result];

}

- (void)awakeFromInsertionInEditingContext:(EOEditingContext *)ctx
{
    [super awakeFromInsertionInEditingContext:ctx];

    // set default values
    if (!budget) 
	budget = [[NSDecimalNumber decimalNumberWithString:@"1000000.00"] retain];
    if (!movies) movies = [NSMutableArray new];    
}

- (NSException *)validateForSave
{
    if ([[self budget] doubleValue] < 0)
	return [NSException validationExceptionWithFormat:@"You're exceeding your budget!"];
   
    return [super validateForSave];  
}

- (void)addToMovies:(id)movie
{
    NSDecimalNumber *newBudget;
    [self willChange];
    newBudget = [[self budget] decimalNumberBySubtracting:[movie valueForKey:@"revenue"]];
    [self setBudget:newBudget];
    [movies addObject:movie];
}

- (void)removeFromMovies:(id)movie
{
    NSDecimalNumber *newBudget;
    [self willChange];
    newBudget = [[self budget] decimalNumberByAdding:[movie valueForKey:@"revenue"]];
    [self setBudget:newBudget];
    [movies removeObject:movie];
}

- (void)buyAllMoviesStarring:(Talent *)talent
{
    NSArray *actorsMovies = [talent moviesStarredIn];
    unsigned i = [actorsMovies count];
    while (i--) {
        id movie = [actorsMovies objectAtIndex:i];
        if (![movies containsObject:movie]) {
	    [self addToMovies:movie];
	}
    }
}


////////////////////////////// ACCESSORS /////////////////////////////////

- (void)setBudget:(NSDecimalNumber *)value
{
    [self willChange];
    [budget autorelease];
    budget = [value retain];
}
- (NSDecimalNumber *)budget { return budget; }

- (void)setName:(NSString *)value
{
    [self willChange];
    [name autorelease];
    name = [value retain];
}
- (NSString *)name { return name; }


- (NSArray *)movies { return movies; }


- (void)dealloc
{
    [budget release];
    [name release];
    [movies release];

    [super dealloc];
}


@end
