//
//  ICFAssetLibraryViewController.m
//  Asset Library Navigator
//
//  Created by Joe Keeley on 4/15/12.
//  Copyright (c) 2012 Explore Systems, Inc. All rights reserved.
//

#import "ICFAssetLibraryViewController.h"
#import "ICFAssetLibraryTableCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ICFAssetGroupViewController.h"
#define kGroupLabelText @"groupLabelText"
#define kGroupInfoText @"groupInfoText"
#define kGroupURL @"groupURL"
#define kGroupPosterImage @"groupPosterImage"

@implementation ICFAssetLibraryViewController

@synthesize assetGroupArray;
@synthesize assetGroupTableView;
@synthesize selectedGroupURL;

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

- (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)dealloc
{
    assetGroupArray = nil;
    selectedGroupURL = nil;
    
}

#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue 
                 sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"ViewAssetGroup"])
	{
        NSIndexPath *indexPath = 
        [assetGroupTableView indexPathForSelectedRow];
        
        NSDictionary *selectedDict = 
        [assetGroupArray objectAtIndex:indexPath.row];
        
        [self setSelectedGroupURL:
         [selectedDict objectForKey:kGroupURL]];

        ICFAssetGroupViewController *aVC = 
        segue.destinationViewController;
        
        [aVC setAssetGroupURL:[self selectedGroupURL]];
        
        [aVC setAssetGroupName:
         [selectedDict objectForKey:kGroupLabelText]];
        
        [assetGroupTableView 
         deselectRowAtIndexPath:indexPath animated:NO];
	}
}

#pragma mark - Table methods
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    NSInteger returnCount = 0;
    
    if (assetGroupArray) {
        returnCount = [assetGroupArray count];
    }
    return returnCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = @"ICFAssetLibraryTableCell";
    ICFAssetLibraryTableCell *cell = (ICFAssetLibraryTableCell *)
    [tableView dequeueReusableCellWithIdentifier:cellID];
    
    NSDictionary *cellDict = 
    [assetGroupArray objectAtIndex:indexPath.row];
    
    [cell.assetGroupNameLabel 
     setText:[cellDict objectForKey:kGroupLabelText]];
    
    [cell.assetGroupInfoLabel 
     setText:[cellDict objectForKey:kGroupInfoText]];
    
    [cell.assetGroupTopImageView 
     setImage:[cellDict objectForKey:kGroupPosterImage]];
    
    return cell;
}

#pragma mark - View lifecycle

- (void)setupAssetData 
{
    ALAssetsLibrary *al = 
    [[ALAssetsLibrary alloc] init];
    
    NSMutableArray *setupArray = [[NSMutableArray alloc] init];
    
void (^enumerateAssetGroupsBlock)(ALAssetsGroup*, BOOL*) = 
^(ALAssetsGroup* group, BOOL* stop) {
    if (group)
    {            
        NSUInteger numAssets = [group numberOfAssets];
        
        NSString *groupName = 
        [group valueForProperty:ALAssetsGroupPropertyName];
        NSLog(@"Grupa: %@, edytowalna: %d",groupName, [group isEditable]);

        NSURL *groupURL = 
        [group valueForProperty:ALAssetsGroupPropertyURL];
        
        NSString *groupLabelText = 
        [NSString stringWithFormat:@"%@ (%d)",groupName, numAssets];
                
        UIImage *posterImage = 
        [UIImage imageWithCGImage:[group posterImage]];
        
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        NSInteger groupPhotos = [group numberOfAssets];

        [group setAssetsFilter:[ALAssetsFilter allVideos]];
        NSInteger groupVideos = [group numberOfAssets];

        NSString *info = @"%d zdjęć, %d filmów w grupie";
        NSString *groupInfoText = 
        [NSString stringWithFormat:info ,groupPhotos, groupVideos];
        
        NSDictionary *groupDict =
        @{kGroupLabelText: groupLabelText,
          kGroupURL:groupURL,
          kGroupPosterImage:posterImage,
          kGroupInfoText:groupInfoText};
                
        [setupArray addObject:groupDict];
    }
    else
    {
        [self setAssetGroupArray:
         [NSArray arrayWithArray:setupArray]];
        
        [assetGroupTableView reloadData];
    }
};
    
    void (^assetGroupEnumErrorBlock)(NSError*) = 
    ^(NSError* error) {
        
        NSString *msgError =
        @"Nie można pobrać grup zasobów. \n"
        "Zmień ustawienia prywatności, aby włączyć uprawnienia \n";
        
        UIAlertView* alertView = 
        [[UIAlertView alloc] initWithTitle:nil 
                                   message:msgError
                                  delegate:self 
                         cancelButtonTitle:@"OK" 
                         otherButtonTitles:nil];
        
        [alertView show];
    };
    
    [al enumerateGroupsWithTypes:ALAssetsGroupAll
                      usingBlock:enumerateAssetGroupsBlock
                    failureBlock:assetGroupEnumErrorBlock];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"Grupy zasobów"];    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self setAssetGroupTableView:nil];
}

- (void)viewWillAppear:(BOOL)animated 
{
    [self setupAssetData];
}

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

@end
