#import "OrderController.h"
#import "ProgramController.h"
#import "Program.h"


@implementation OrderController

- (void)prepareOrder:(id)sender
{
    int result;
    Program *selectedProgram = [programController selectedProgram];

    [orderTitleField setStringValue:[selectedProgram title]];
    [orderChannelField setStringValue:[selectedProgram channel]];
    [orderCostField setStringValue:[selectedProgram cost]];
    [orderDateField setStringValue:[[selectedProgram broadcastDate] description]];
    
    [buyerNameField setStringValue:@""];
    [creditCardField setStringValue:@""];

    result = [NSApp runModalForWindow:orderPanel];
    switch (result) {
        case NSRunStoppedResponse:
            [self confirmOrder];
            break;
        case NSRunAbortedResponse:
            [self cancelOrder];
            break;
    }
    return;
}


- (void)cancelClicked:(id)sender
{
    [orderPanel orderOut:nil];
    [NSApp abortModal];
    return;
}

- (void)okClicked:(id)sender
{
    if (![self verifyCreditCard]) return;
    [orderPanel orderOut:nil];
    [NSApp stopModal];
    return;
}

- (void)cancelOrder
{
    NSString *status = [NSString stringWithFormat:@"Order for %@ was cancelled\n", [orderTitleField stringValue]];

    NSRunAlertPanel(@"Order Canceled", status, nil, nil, nil);
    return;
}

- (void)confirmOrder
{
    NSString *status = [NSString stringWithFormat:@"%@ ordered %@ using card #%@\n",
        [buyerNameField stringValue], [orderTitleField stringValue],
        [creditCardField stringValue]];

    NSRunAlertPanel(@"Order Placed", status, nil, nil, nil);
    return;
}

- (BOOL)verifyCreditCard
{
    if ([[buyerNameField stringValue] isEqual:@""]) {
        NSRunAlertPanel(@"No Customer Name",
            @"You must enter a customer's name.", nil, nil, nil);
        return NO;
    }

    if ([[creditCardField stringValue] isEqual:@""]) {
        NSRunAlertPanel(@"Invalid Card",
            @"You must specify a valid credit card number for %@.",
            nil, nil, nil, [buyerNameField stringValue]);
        return NO;
    }

    return YES;
}

@end
