//
//  FlipsideViewController.m
//  MusicLibraryClient
//
//  Created by Chris Adamson on 5/5/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 "FlipsideViewController.h"


@implementation FlipsideViewController

@synthesize delegate;
@synthesize searchController;
@synthesize searchTypeControl;
@synthesize queueTable;


- (void)viewDidLoad {
	NSLog (@"viewDidLoad. %@", newPlaybackQueue);
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];

//START:code.FlipsideViewController.initarrays
	[newPlaybackQueue release];
	newPlaybackQueue = [[NSMutableArray alloc] init];
//END:code.FlipsideViewController.initarrays
}


//START:code.FlipsideViewController.done
- (IBAction)done {
	if ([newPlaybackQueue count]) {
		MPMusicPlayerController *iPodController =
			[MPMusicPlayerController iPodMusicPlayer];
		[iPodController stop];
		MPMediaItemCollection *queueCollection =
			[MPMediaItemCollection collectionWithItems:
				newPlaybackQueue];
		[iPodController setQueueWithItemCollection: queueCollection];
		[iPodController play];
	}
	// provided by xcode template to flip back
	[self.delegate flipsideViewControllerDidFinish:self];
}
//END:code.FlipsideViewController.done





#pragma mark Table view methods

//START:code.FlipsideViewController.tablesectionsandrows
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
		numberOfRowsInSection:(NSInteger)section {
	if (tableView == queueTable) {
		return [newPlaybackQueue count];
	} else {
		return [searchResults count];
	}
}
//END:code.FlipsideViewController.tablesectionsandrows


// provide queue length header (only for queueTable)
//START:code.FlipsideViewController.titleforheader
- (NSString *)tableView:(UITableView *)tableView
		titleForHeaderInSection:(NSInteger)section {
	if (tableView == queueTable) {
		return [NSString stringWithFormat:
			@"Queue (%d songs)", [newPlaybackQueue count]];
	} else {
		return nil;
	}
}
//END:code.FlipsideViewController.titleforheader


//START:code.FlipsideViewController.cellforrowatindexpath
- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell =
		[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
			initWithStyle:UITableViewCellStyleSubtitle
			reuseIdentifier:CellIdentifier] autorelease];
    }
	// Configure the cell
	MPMediaItem *anItem = nil;
	if (tableView == queueTable) {
		anItem = [newPlaybackQueue objectAtIndex:indexPath.row];
	} else {
		anItem = [searchResults objectAtIndex:indexPath.row];
	}
	cell.textLabel.text =
		[anItem valueForProperty:MPMediaItemPropertyTitle];
	cell.detailTextLabel.text =
		[anItem valueForProperty:MPMediaItemPropertyArtist];	
	return cell;
}
//END:code.FlipsideViewController.cellforrowatindexpath


//START:code.FlipsideViewController.didselectrowatindexpath
- (void)tableView:(UITableView *)tableView
		didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (tableView != queueTable) {
		// add item from search results to queue
		[newPlaybackQueue addObject:
			[searchResults objectAtIndex:indexPath.row]];
		[queueTable reloadData];
		[tableView deselectRowAtIndexPath:indexPath animated:NO];
		[searchController setActive:NO animated:YES];
		searchResults = nil;
	} else {
		[tableView deselectRowAtIndexPath:indexPath animated:NO];
	}
}
//END:code.FlipsideViewController.didselectrowatindexpath

#pragma mark search logic

//START:code.FlipsideViewController.updatesearchresults
- (void) updateSearchResults {
	NSString *searchText = searchController.searchBar.text;
	MPMediaQuery *query = [MPMediaQuery songsQuery];
	switch (searchTypeControl.selectedSegmentIndex) {
		case 0: {
			MPMediaPropertyPredicate *titlePredicate =
			[MPMediaPropertyPredicate predicateWithValue:searchText
				forProperty:MPMediaItemPropertyTitle
				comparisonType: MPMediaPredicateComparisonContains];
			[query addFilterPredicate:titlePredicate];
			break;
		}
		case 1: {
			MPMediaPropertyPredicate *artistPredicate =
			[MPMediaPropertyPredicate predicateWithValue:searchText
				forProperty:MPMediaItemPropertyArtist
				comparisonType: MPMediaPredicateComparisonContains];
			[query addFilterPredicate:artistPredicate];
			break;
		}
		case 2: {
			MPMediaPropertyPredicate *albumPredicate =
			[MPMediaPropertyPredicate predicateWithValue:searchText
				forProperty:MPMediaItemPropertyAlbumTitle
				comparisonType: MPMediaPredicateComparisonContains];
			[query addFilterPredicate:albumPredicate];
			break;
		}
		default: {
			// unknown segment type - just return everything
			query = [MPMediaQuery songsQuery];
		}
	}
	
	[searchResults release];
	searchResults = query.items;
	[searchResults retain];
}
//END:code.FlipsideViewController.updatesearchresults

//START:code.FlipsideViewController.searchtypechanged
- (IBAction) searchTypeChanged {
	[self updateSearchResults];
	if (searchController.active == YES) {
		[searchController.searchResultsTableView reloadData];
	}
}
//END:code.FlipsideViewController.searchtypechanged

# pragma mark UISearchBarDelegate methods

// - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//START:code.FlipsideViewController.searchbardelegatemethods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	[self updateSearchResults];
	[searchController.searchResultsTableView reloadData];
}

- (void) searchBarCancelButtonClicked: (UISearchBar *) searchBar {
	searchResults = nil;
}
//END:code.FlipsideViewController.searchbardelegatemethods

/*
 // 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];
 }
 */

# pragma mark browse button
//START:code.FlipsideViewController.handlebrowsetapped
- (IBAction) handleBrowseTapped {
	MPMediaPickerController *pickerController =
		[[MPMediaPickerController alloc]
			initWithMediaTypes: MPMediaTypeMusic];
	pickerController.prompt = @"Add songs to queue";
	pickerController.allowsPickingMultipleItems = YES;
	pickerController.delegate = self;
	[self presentModalViewController:pickerController animated:YES];
	[pickerController release];
}
//END:code.FlipsideViewController.handlebrowsetapped

# pragma mark MPMediaPickerControllerDelegate methods

//START:code.FlipsideViewController.mediapickerdelegate
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker
		didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {	
	[self dismissModalViewControllerAnimated:YES];
	[newPlaybackQueue addObjectsFromArray:mediaItemCollection.items];
	[queueTable reloadData];
}

- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {
	[self dismissModalViewControllerAnimated:YES];	
}
//END:code.FlipsideViewController.mediapickerdelegate


# pragma mark VC life-cycle stuff

/*
 // 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 any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


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


@end
