/*
        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 "Transaction.h"
#import "OneObjectDataSource.h"
#import "ProductReturn.h"

#import <BusinessLogic/BusinessLogic.h>
#import <BusinessLogic/NSObjectAdditions.h>
#import <BusinessLogic/Fee.h>

@implementation Transaction

- initWithCustomerGlobalID:(EOGlobalID *)gid
{
    EOActionAssociation *association;

    [super init];

    //
    // Load the nib file
    //
    // Make sure the nib create a NEW editing context
    //
    [EOEditingContext setSubstitutionEditingContext:nil];

    if (![NSBundle loadNibNamed:@"Transaction" owner:self]) {
        NSLog(@"Unable to load nib file: Transaction.nib, exiting");
        exit(1);
    }

    //
    // Create and install the association
    //
    association = [[[EOActionAssociation alloc] initWithObject:insertButton] autorelease];
    [association bindAspect:@"action" displayGroup:customerDisplayGroup key:@"rentUnit:"];
    [association bindAspect:@"argument" displayGroup:unitDisplayGroup key:@"self"];
    [association bindAspect:@"enabled" displayGroup:unitDisplayGroup key:@"isAvailableForRent"];
    [association establishConnection];

    //
    // Install the customer in a custom datasource
    //
    [customerDisplayGroup setDataSource:[[[OneObjectDataSource alloc] initWithGlobalID:gid editingContext:[[customerDisplayGroup dataSource] editingContext]] autorelease]];

    // Fetch the customer
    //
    [customerDisplayGroup fetch];

    return self;
}

- (void)displayGroup:(EODisplayGroup *)displayGroup didFetchObjects:(NSArray *)objects
{
    NSDecimalNumber *cost = [objects sumArrayWithKey:@"amount"];
    NSDecimalNumber *taxToAdd = [cost decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@".085"]];

    [total setObjectValue:cost];
    [tax setObjectValue:taxToAdd];
    [totalDue setObjectValue:[cost decimalNumberByAdding:taxToAdd]];
}

- (void)paymentDone:(id)sender
{
    EOEditingContext *ec = [[customerDisplayGroup dataSource] editingContext];
    EOUndoManager *manager = [ec undoManager];
    BOOL saveSucceed = YES;

    // begin grouping before payments so we can roll them back upon error
    [manager beginUndoGrouping];  

    // Mark all the fees as paid.
    [[feesDisplayGroup displayedObjects] makeObjectsPerform:@selector(pay)];

    // Attempt to save changes and catch an errors
    NS_DURING
        [ec saveChanges];
    NS_HANDLER
        NSRunAlertPanel(@"Ouch", [localException reason], nil, nil, nil);
        saveSucceed = NO;
    NS_ENDHANDLER

    [manager endUndoGrouping];

    if(saveSucceed && ![ec hasChanges]) {
        // I should release everything.  For now, just close window
        // and leak everything !
        NSRunAlertPanel(@"Rental", @"Payment successfully recorded", nil, nil, nil);
        [[insertButton window] close];
    } else {
        // Undo the payment.
        [manager disableUndoRegistration];  // disable so we don't register redos
        [manager undo];
        [manager reenableUndoRegistration];
    }
}

- (void)productReturn:(id)sender
{
    id selectedCustomer = [memberDisplayGroup selectedObject];
    EOGlobalID *customerGID;

    customerGID = [[selectedCustomer editingContext] globalIDForObject:selectedCustomer];

    [[ProductReturn alloc] initWithCustomerGlobalID:customerGID parentEditingContext:[selectedCustomer editingContext]];
}

- (void)revert:(id)sender
{
    EOEditingContext *editingContext = [[customerDisplayGroup dataSource] editingContext];

    [editingContext revert:sender];
}

@end
