//
//  RootViewController.m
//  MovieTable
//
//  Created by Chris Adamson on 6/1/09.
//  Copyright Subsequently and Furthermore, Inc. 2009. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//

#import "RootViewController.h"

NSString *testMovieData[][3]  = {
	{@"Left", @"110000000", @"Fly away on the adventure of your life"},
	{@"CHARL-E", @"120000000", @"The little robot friend that will melt your heart, with his flamethrower"},
	{@"Bouillabaisse", @"130000000", @"C'est magnifique! Le meillure entrée pour déjuner!"},
	{@"Vehicles", @"140000000", @"Let's drive off for a grand adventure"},
	{@"The Extraordinary Family", @"150000000", @"The casserole isn't the only thing \"super\" in this household"},
	{@"Searching for Aronnax", @"160000000", @"This summer's fishiest family film"},
	{@"Creatures, LLC", @"170000000", @"They're just two ordinary guys, doing their job"},
	{@"Plaything Anecdote 2", @"180000000", @"Just like the first one, but better"},
	{@"An Insect's Existence", @"190000000", @"This movie will bug you more than most."},
	{@"Plaything Anecdote", @"200000000", @"Did you think your dolls were really alive? Well, they are."},
};



@implementation RootViewController

@synthesize movieEditor, nibLoadedCell;


-(void) loadTestData {
	// fill moviesArray with test data
	for (int i=0; i< 10; i++) {
		Movie *aMovie = [[Movie alloc] init];
		aMovie.title = testMovieData[i][0];
		aMovie.boxOfficeGross = [NSNumber numberWithInt: [testMovieData[i][1] intValue]];
		aMovie.summary = testMovieData[i][2];
		[moviesArray addObject: aMovie];
		[aMovie release];
	}
}

- (void)viewDidLoad {
    [super viewDidLoad];

	// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

	self.navigationItem.leftBarButtonItem = self.editButtonItem;
	self.editing = NO;
	
	moviesArray = [[NSMutableArray alloc] init];
	
	[self loadTestData];
}

/*
 */
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	NSLog (@"viewWillAppear");
	// update table view if a movie was edited
	if (editingMovie) {
		NSIndexPath *updatedPath = [NSIndexPath
			indexPathForRow: [moviesArray indexOfObject: editingMovie] inSection: 0];
		NSArray *updatedPaths = [NSArray arrayWithObject:updatedPath];
		[self.tableView reloadRowsAtIndexPaths:updatedPaths withRowAnimation:NO];
		editingMovie = nil;
	}
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release anything that can be recreated in viewDidLoad or on demand.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // return 0;
	return [moviesArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//START:code.RootViewController.loadnibnamed
    if (cell == nil) {
		[[NSBundle mainBundle] loadNibNamed:@"MovieTableCell" // <label id="code.MovieTable02.RootViewController.loadnibnamed.load"/>
			owner:self options:NULL]; 
		cell = nibLoadedCell; // <label id="code.MovieTable02.RootViewController.loadnibnamed.assign"/>
    }
//END:code.RootViewController.loadnibnamed
    
//START:code.RootViewController.configurecell
	// Configure the cell.
	Movie *aMovie = [moviesArray objectAtIndex:indexPath.row];
	UILabel *titleLabel = (UILabel*) [cell viewWithTag:1];
	titleLabel.text = aMovie.title;
	UILabel *boxOfficeLabel = (UILabel*) [cell viewWithTag:2];
	boxOfficeLabel.text =  [NSString stringWithFormat: @"%d",
		[aMovie.boxOfficeGross intValue]];
	UILabel *summaryLabel = (UILabel*) [cell viewWithTag:3];
	summaryLabel.text =  aMovie.summary;
	return cell;
//END:code.RootViewController.configurecell
}



/*
// Override to support row selection in the table view.
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // Navigation logic may go here -- for example, create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController animated:YES];
	// [anotherViewController release];

	editingMovie = [moviesArray objectAtIndex:indexPath.row];
	movieEditor.movie = editingMovie;
	[self.navigationController pushViewController:movieEditor animated:YES];
}


/*
// Override to support conditional editing of the table view.
*/
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}


/*
// Override to support editing the table view.
 */
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
		[moviesArray removeObjectAtIndex: indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

-(void) setEditing: (BOOL) editing animated: (BOOL) animated {
	NSLog (@"VC got setEditing:animated");
	[super setEditing: editing animated: animated];
}

# pragma mark IBActions


-(IBAction) handleAddTapped {
	NSLog (@"handleAddTapped");
	Movie *newMovie = [[Movie alloc] init];
	[moviesArray addObject: newMovie];
	editingMovie = newMovie;
	movieEditor.movie = editingMovie;
	[self.navigationController pushViewController:movieEditor animated:YES];
	// update UITableView (in background) with new member
	NSIndexPath *newMoviePath = [NSIndexPath indexPathForRow: [moviesArray count]-1 inSection:0];
	NSArray *newMoviePaths = [NSArray arrayWithObject:newMoviePath];
	[self.tableView insertRowsAtIndexPaths:newMoviePaths withRowAnimation:NO];
}


# pragma mark cleanup

- (void)dealloc {
    [super dealloc];
}


@end

