/*
        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/Member.h>
#import <BusinessLogic/Guest.h>
#import <BusinessLogic/CreditCard.h>
#import <BusinessLogic/NSObjectAdditions.h>

@implementation Member

- (void)awakeFromInsertionInEditingContext:(EOEditingContext *)ctx
{
    // set default values
    // Default membership date to today
    if (!memberSince) 
        memberSince = [[NSCalendarDate date] retain];

    if (!guests)
        guests = [NSMutableArray new];

    [super awakeFromInsertionInEditingContext:ctx];
}

- (Member *)member {
    // We are a member (not a guest) so we return ourselves
    return self;
}

- (NSArray *)allRentals
{
    NSEnumerator *guestEnumerator = [guests objectEnumerator];
    NSMutableArray *array = [NSMutableArray array];
    Guest *next;

    [array addObjectsFromArray:[super allRentals]];
    while(next = [guestEnumerator nextObject])
        [array addObjectsFromArray:[next allRentals]];

    return array;
}

- (void)dealloc
{
    [city release];
    [memberSince release];
    [phone release];
    [state release];
    [streetAddress release];
    [zip release];
    [creditCard release];
    [guests release];
    [super dealloc];
}

- (BOOL)hasCreditCard
{
    return (creditCard) ? YES : NO;
}

- (NSDecimalNumber *)costRestriction
{
    return [self hasCreditCard] ? [creditCard limit] : [NSDecimalNumber zero];
}

// Give guests a 20% increase in rental limits
- (void)boostRestrictions
{
    NSDecimalNumber *rate = [NSDecimalNumber decimalNumberWithString:@"1.50"];  // 50% boost
    int i;
    
    for (i = [guests count] - 1; i >= 0; i--) {
        Guest *guest = [guests objectAtIndex:i];
        [guest setCostRestriction:[[guest costRestriction] decimalNumberByMultiplyingBy:rate]];
    }
}

- (NSString *)inverseForRelationshipKey:(NSString *)relationshipKey
{
    // It's normally not necessary to explicitly define this method,
    // since the EOModel does it for us (via EOClassDescription).  In
    // this case EORelationship can't spot the inverse because we don't
    // join on the same set of keys in the member and creditCard relationships
    if ([relationshipKey isEqual:@"creditCard"])
        return @"member";
    return [super inverseForRelationshipKey:relationshipKey];
}

@end
