/*
        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 <BusinessLogic/Unit.h>
#import <BusinessLogic/Product.h>
#import <BusinessLogic/Rental.h>

@implementation Unit

- (Product *)product
{
    return product;
}

- (NSException *)validateForSave
{
    // this method will be called before we are inserted or updated in the database
    unsigned rentalsOut = 0;
    NSEnumerator *rentalsEnumerator = [rentals objectEnumerator];
    Rental *next;

    while(next = [rentalsEnumerator nextObject]) {
        rentalsOut += [next isOut] ? 1 : 0;
        if(rentalsOut > 1)
            return [NSException validationExceptionWithFormat:@"The unit %@ of product %@ may not be rented twice", unitID, [product name]];
    }

    return [super validateForSave];  // pass the check on to the EOClassDesciption
}

- (BOOL)isAvailableForRent
{
    NSEnumerator *rentalsEnumerator = [rentals objectEnumerator];
    Rental *next;

    while(next = [rentalsEnumerator nextObject])
        if([next isOut]) return NO;

    return YES;
}

- (NSString *)inStockString
{
    return [self isAvailableForRent] ? @"Yes" : @"No";
}

- (void)dealloc
{
    [unitID release];
    [notes release];
    [dateAcquired release];
    [product release];
    [rentals release];
    [super dealloc];
}

- (void)awakeFromInsertionInEditingContext:(EOEditingContext *)editingContext
{
    // set our defaults
    if(!dateAcquired) 
        dateAcquired = [[NSCalendarDate calendarDate] retain];
}

- description { return [self eoDescription]; }

@end
