//
//  MainViewController.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 "MainViewController.h"
#import "MainView.h"

#define EMPTY_ALBUM_FILE_NAME @"empty-album-200x200"

@implementation MainViewController

@synthesize playPauseButton;
@synthesize currentTimeLabel;
@synthesize currentTimeSlider;
@synthesize currentItemDurationLabel;
@synthesize currentItemTitleLabel;
@synthesize currentItemArtistLabel;
@synthesize currentItemAlbumLabel;
@synthesize currentItemArtworkView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}

#pragma mark GUI update methods

//START:code.MainViewController.updateplaystate
- (void) updatePlayState {
	MPMusicPlayerController *iPodController = 
		[MPMusicPlayerController iPodMusicPlayer]; 
	playPauseButton.selected =
		(iPodController.playbackState == MPMusicPlaybackStatePlaying); 
}
//END:code.MainViewController.updateplaystate


/* this version quoted in the book doesn't do an if (!userIsScrubbing), as the
	scrubbing stuff hasn't been introduced at that point.
//START:code.MainViewController.updateipoditemtime
- (void) updateCurrentiPodItemTime {
	MPMusicPlayerController *iPodController =
		[MPMusicPlayerController iPodMusicPlayer];
	MPMediaItem *nowPlayingItem= [iPodController nowPlayingItem];
	if (nowPlayingItem == nil) {
		currentTimeLabel.text = @"00:00";
	} else {
		double currentTime = iPodController.currentPlaybackTime;
		currentTimeLabel.text = [NSString stringWithFormat: @"%02d:%02d",
			(int) currentTime/60,
			(int) currentTime%60];		
		currentTimeSlider.value = (float) currentTime;
	}
}
//END:code.MainViewController.updateipoditemtime
*/
 
- (void) updateCurrentiPodItemTime {
	MPMusicPlayerController *iPodController =
		[MPMusicPlayerController iPodMusicPlayer];
	MPMediaItem *nowPlayingItem= [iPodController nowPlayingItem];
	if (nowPlayingItem == nil) {
		currentTimeLabel.text = @"00:00";
	} else {
		double currentTime = iPodController.currentPlaybackTime;
		currentTimeLabel.text = [NSString stringWithFormat: @"%02d:%02d",
						(int) currentTime/60,
						(int) currentTime%60];		
		if (! userIsScrubbing)
			currentTimeSlider.value = (float) currentTime;
	}
}



/* this version quoted in the book lacks currentItemDurationLabel, as the formatting stuff 
   hasn't been introduced at that point
//START:code.MainViewController.updatecurrentipoditemmetadata
- (void) updateCurrentiPodItemMetadata {
	MPMusicPlayerController *iPodController =
		[MPMusicPlayerController iPodMusicPlayer];
	MPMediaItem *nowPlayingItem= [iPodController nowPlayingItem];
	if (nowPlayingItem == nil) {
		currentTimeSlider.maximumValue = 1.0;
		currentTimeSlider.value = 0;
		currentItemDurationLabel.text = @"00:00";
		currentItemTitleLabel.text = @"(nothing playing)";
		currentItemArtistLabel.text = nil;
		currentItemAlbumLabel.text = nil;
		currentItemArtworkView.image = emptyAlbumImage;
	} else {
		NSNumber *durationNumber = [nowPlayingItem  // <label id="code.MainViewController.updatecurrentipoditemmetadata.duration"/>
			valueForProperty:MPMediaItemPropertyPlaybackDuration];
		currentTimeSlider.maximumValue = [durationNumber floatValue];
		currentItemTitleLabel.text = [nowPlayingItem
			valueForProperty:MPMediaItemPropertyTitle];
		currentItemArtistLabel.text = [nowPlayingItem
			valueForProperty:MPMediaItemPropertyArtist];
		currentItemAlbumLabel.text = [nowPlayingItem
			valueForProperty:MPMediaItemPropertyAlbumTitle];
		MPMediaItemArtwork *coverArt = [nowPlayingItem // <label id="code.MainViewController.updatecurrentipoditemmetadata.coverart"/>
			valueForProperty:MPMediaItemPropertyArtwork];
		if (coverArt) 
			currentItemArtworkView.image = [coverArt
				imageWithSize: currentItemArtworkView.frame.size];
		else
			currentItemArtworkView.image = emptyAlbumImage;
		
	}
}
//END:code.MainViewController.updatecurrentipoditemmetadata
 */


- (void) updateCurrentiPodItemMetadata {
	MPMusicPlayerController *iPodController = [MPMusicPlayerController iPodMusicPlayer];
	MPMediaItem *nowPlayingItem= [iPodController nowPlayingItem];
	NSLog (@"%@", nowPlayingItem);
	if (nowPlayingItem == nil) {
		currentTimeSlider.maximumValue = 1.0; // meaningless, but should be > min
		currentTimeSlider.value = 0;
		currentItemDurationLabel.text = @"00:00";
		currentItemTitleLabel.text = @"(nothing playing)";
		currentItemArtistLabel.text = nil;
		currentItemAlbumLabel.text = nil;
		currentItemArtworkView.image = emptyAlbumImage;
	} else {
		NSNumber *durationNumber =  [nowPlayingItem valueForProperty:MPMediaItemPropertyPlaybackDuration];
		currentTimeSlider.maximumValue = [durationNumber floatValue];
		currentItemDurationLabel.text = [NSString stringWithFormat: @"%02d:%02d",
					[durationNumber intValue] / 60,
					[durationNumber intValue] % 60];
		currentItemTitleLabel.text = [nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];
		currentItemArtistLabel.text = [nowPlayingItem valueForProperty:MPMediaItemPropertyArtist];
		currentItemAlbumLabel.text = [nowPlayingItem valueForProperty:MPMediaItemPropertyAlbumTitle];
		MPMediaItemArtwork *coverArt = [nowPlayingItem valueForProperty:MPMediaItemPropertyArtwork];
		if (coverArt) 
			currentItemArtworkView.image = [coverArt imageWithSize: currentItemArtworkView.frame.size];
		else
			currentItemArtworkView.image = emptyAlbumImage;

	}
}

#pragma mark notification callbacks

//START:code.MainViewController.notificationcallbacks
-(void) playbackStateChanged: (NSNotification*) notification {
	[self updatePlayState];
}

-(void) nowPlayingItemChanged: (NSNotification*) notification {
	[self updatePlayState];
	[self updateCurrentiPodItemMetadata];
	[self updateCurrentiPodItemTime];
}
//END:code.MainViewController.notificationcallbacks



#pragma mark IBActions
//START:code.MainViewController.handleplaypausetapped
- (IBAction) handlePlayPauseTapped {
	MPMusicPlayerController *iPodController =
		[MPMusicPlayerController iPodMusicPlayer];
	if (iPodController.playbackState == MPMusicPlaybackStatePlaying) {
		[iPodController pause];
	} else {
		[iPodController play];
	}
}
//END:code.MainViewController.handleplaypausetapped



//START:code.MainViewController.handlescrubbertouch
-(IBAction) handleScrubberTouchDown {
	userIsScrubbing = YES;
}

-(IBAction) handleScrubberTouchUp {
	userIsScrubbing = NO;
}
//END:code.MainViewController.handlescrubbertouch


//START:code.MainViewController.handlescrub
-(IBAction) handleScrub {
	MPMusicPlayerController *iPodController =
		[MPMusicPlayerController iPodMusicPlayer];
	iPodController.currentPlaybackTime = currentTimeSlider.value;
}
//END:code.MainViewController.handlescrub


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


#pragma mark flip methods (from template)

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller {
    
	[self dismissModalViewControllerAnimated:YES];
}


- (IBAction)showInfo {    
	
	FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
	controller.delegate = self;
	
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:controller animated:YES];
	
	[controller release];
}

#pragma mark VC lifecycle methods

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 */
- (void)viewDidLoad {
	[super viewDidLoad];
	
	// create the empty album graphic
//START:code.MainViewController.initemptyalbumimage
	emptyAlbumImage = [[UIImage alloc] initWithContentsOfFile:
		[[NSBundle mainBundle]
			pathForResource:EMPTY_ALBUM_FILE_NAME ofType:@"png"]];
//END:code.MainViewController.initemptyalbumimage
		
//START:code.MainViewController.setuptimer
	// create timer to update clock
	currentTimeUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
		target:self selector:@selector(updateCurrentiPodItemTime)
		userInfo:NULL repeats:YES];
//END:code.MainViewController.setuptimer
	
	// update displays
//START:code.MainViewController.viewdidloadupdatecalls
	[self updatePlayState];
	[self updateCurrentiPodItemMetadata];
	[self updateCurrentiPodItemTime];
//END:code.MainViewController.viewdidloadupdatecalls
	userIsScrubbing = NO;
	
	// get notifications of state changes and item changes
//START:code.MainViewController.addnotificationobservers
	[[NSNotificationCenter defaultCenter] addObserver:self 
			selector: @selector (playbackStateChanged:) 
			name:@"MPMusicPlayerControllerPlaybackStateDidChangeNotification" 
			object:nil]; 
	[[NSNotificationCenter defaultCenter] addObserver:self 
			selector: @selector (nowPlayingItemChanged:) 
			name:@"MPMusicPlayerControllerNowPlayingItemDidChangeNotification" 
			object:nil]; 
	[[MPMusicPlayerController iPodMusicPlayer] beginGeneratingPlaybackNotifications];
//END:code.MainViewController.addnotificationobservers
}


/*
 // 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
