//
//  DetailViewController.m
//  SearchExample
//
//  Created by Patrick Crosby on 4/27/10.
//  Copyright XB Labs, LLC 2010. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController (Private)
- (void)configureView;
@end

@implementation DetailViewController

@synthesize toolbar = _toolbar, detailItem = _detailItem, detailDescriptionLabel = _detailDescriptionLabel;
@synthesize myPopoverController = _myPopoverController;

/*
 When setting the detail item, update the view and dismiss the popover controller if it's showing.
 */
- (void)setDetailItem:(id)newDetailItem {
    if (_detailItem != newDetailItem) {
        [_detailItem release];
        _detailItem = [newDetailItem retain];
        
        // Update the view.
        [self configureView];
    }

    if (_myPopoverController != nil) {
        [_myPopoverController dismissPopoverAnimated:YES];
    }        
}

- (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc {
    
    barButtonItem.title = @"Root List";
    NSMutableArray *items = [[self.toolbar items] mutableCopy];
    [items insertObject:barButtonItem atIndex:0];
    [self.toolbar setItems:items animated:YES];
    [items release];
    self.myPopoverController = pc;
}

// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
    
    NSMutableArray *items = [[self.toolbar items] mutableCopy];
    [items removeObjectAtIndex:0];
    [self.toolbar setItems:items animated:YES];
    [items release];
    self.myPopoverController = nil;
}

// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.myPopoverController = nil;
}

- (void)dealloc {
    [_myPopoverController release];
    [_toolbar release];
    
    [_detailItem release];
    [_detailDescriptionLabel release];
    [super dealloc];
}

@end

@implementation DetailViewController (Private)

- (void)configureView {
    // Update the user interface for the detail item.
    self.detailDescriptionLabel.text = [self.detailItem description];   
}

@end
