//
//  BandsViewController.m
//  RecordCollection
//
//  Created by Gloria Hedlund on 3/25/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BandsViewController.h"
#import "AlbumsViewController.h"
#import "SongsViewController.h"

@interface BandsViewController ()

@property (nonatomic, strong) NSDictionary *recordCollection;
@property (nonatomic, strong) NSArray *categories;
@property (nonatomic, strong) NSArray *bands;
@property (nonatomic, weak) AlbumsViewController *albumsViewController;
// JUST FOR THE CASE OF HAVING SOUNDTRACKS (No Bands) I ALSO NEED THIS:
@property (nonatomic, weak) SongsViewController *songsViewController;

@end

@implementation BandsViewController

@synthesize segue = _segue;
@synthesize recordCollection = _recordCollection, categories = _categories, bands = _bands;
@synthesize albumsViewController = _albumsViewController, songsViewController = _songsViewController;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // read words from words.plist into a NSArray
    NSBundle *mainBundle = [NSBundle bundleForClass:[self class]];
    NSString *path = [mainBundle pathForResource:@"Records" ofType:@"plist"];
    self.recordCollection = [NSDictionary dictionaryWithContentsOfFile:path];
    self.categories = [[self.recordCollection allKeys] sortedArrayUsingSelector:@selector(compare:)];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [self.categories count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    self.bands = [self.recordCollection objectForKey:[self.categories objectAtIndex:section]];
    return [self.bands count];
}

// I ADDED THIS OPTIONAL UITABLEVIEWDELEGATE METHOD IN MANUALLY - THE STUB WAS NOT INCLUDED WITH UITABLEVIEWCONTROLLER
// To show section titles as Headers
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return [self.categories objectAtIndex:section];
}

// In this method, we first get the information that we want to show from our MODEL and then 
// set up our VIEW and tell it what to show
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // GET INFO FROM MODEL
    // Please note that the allKeys method is not guaranteed to return an array in the same order
    // every time - to be sure you get the same order back, you need to sort this yourself
    NSString *category = [self.categories objectAtIndex:indexPath.section];
    self.bands = [[self.recordCollection objectForKey:category] allKeys];
    self.bands = [self.bands sortedArrayUsingSelector:@selector(compare:)];
    
    // SET UP THE VIEW
    // Note that we also have a special case of soundtracks, in which it is the 
    // Album titles showing (not bands) and we want these cells to link to 
    // Song titles (not Album titles)
    UITableViewCell *cell;
    if (![category isEqualToString:@"Soundtracks"]){
        // Make this cell identifier match whatever you have in your storyboard
        static NSString *CellIdentifier = @"Band Name";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    }
    else {
        static NSString *CellIdentifier = @"Soundtrack Name";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    }
    cell.textLabel.text = [self.bands objectAtIndex:indexPath.row];
    return cell;
}

/*
// 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
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

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

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *categoryKey = [self.categories objectAtIndex:indexPath.section];
    
    self.bands = [[self.recordCollection objectForKey:categoryKey] allKeys];
    self.bands = [self.bands sortedArrayUsingSelector:@selector(compare:)];
    
    // Now there is one special category "Soundtracks" that actually does not have "bands", but is displaying
    // the album titles themselves.  If we tried to click on a soundtrack title to get more titles (i.e. an
    // NSDictionary), our program would CRASH because the model is not storing an NSDictionary under 
    // Each Soundtrack Album title - it is storing an NSArray of song titles.
    
    if (![categoryKey isEqualToString:@"Soundtracks"]) {
        NSString *bandKey = [self.bands objectAtIndex:indexPath.row];
        NSDictionary *bandsAndAlbums = [self.recordCollection objectForKey:categoryKey];
        NSDictionary *albums = [bandsAndAlbums objectForKey:bandKey];
        [self.albumsViewController setAlbums:albums];
    }
    // Do something else for the soundtrack cells
    else {
        NSString *soundTrackKey = [self.bands objectAtIndex:indexPath.row];
        // we know categoryKey == @"Soundtracks" 
        NSArray *songs = [[self.recordCollection objectForKey:categoryKey] objectForKey:soundTrackKey];
        [self.songsViewController setSongs:songs];
    }
    
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"View Albums"]){
        self.albumsViewController = segue.destinationViewController;
    }
    if ([segue.identifier isEqualToString:@"View Soundtrack Songs"]){
        self.songsViewController = segue.destinationViewController;
    }
}

@end
