#import "Money.h"

#import "MoneyBag.h"

@implementation Money

- (id)initWithAmount:(int)amount currency:(NSString *)currency {
    self = [super init];
    fAmount = amount;
    fCurrency = [currency retain];
    return self;
}

- (void)dealloc {
    [fCurrency release];
}

- (id<IMoney>)add:(id<IMoney>)money {
    return [money addMoney:self];
}

- (id<IMoney>)addMoney:(Money *)money {
    if ([[money currency] isEqualToString:[self currency]])
        return [[[Money alloc] initWithAmount:[self amount] + [money amount] currency:[self currency]] autorelease];
    return [[[MoneyBag alloc] initWithMoney:self money:money] autorelease];
}

- (id<IMoney>)addMoneyBag:(MoneyBag *)bag {
    return [bag addMoney:self];
}

- (int)amount {
    return fAmount;
}

- (NSString *)currency {
    return fCurrency;
}

- (BOOL)isEqual:(id)anObject {
    if ([self isZero])
        if ([anObject conformsToProtocol:@protocol(IMoney)])
            return [anObject isZero];
    if ([anObject isMemberOfClass:[Money class]]) {
        Money *aMoney = (Money *)anObject;
        return [[aMoney currency] isEqualToString:[self currency]] &&
            [self amount] == [aMoney amount];
    }
    return NO;
}

- (BOOL)isZero {
    return [self amount] == 0;
}

- (id<IMoney>)multiply:(int)factor {
    return [[[Money alloc] initWithAmount:[self amount] * factor currency:[self currency]] autorelease];
}

- (id<IMoney>)negate {
    return [[[Money alloc] initWithAmount:-[self amount] currency:[self currency]] autorelease];
}

- (id<IMoney>)subtract:(id<IMoney>)money {
    return [self add:[money negate]];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"[%d %@]", [self amount], [self currency]];
}

@end
