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

#import "ICFAssetGroupViewController.h"
#import "ICFAssetGroupTableCell.h"
#import "ICFAssetViewController.h"

@interface ICFAssetGroupViewController () 
- (void)retrieveAssetGroupByURL;
- (void)enumerateGroupAssetsForGroup:(ALAssetsGroup *)group;
@end

@implementation ICFAssetGroupViewController

@synthesize assetArray;
@synthesize assetGroupURL;
@synthesize assetGroupName;
@synthesize assetTableView;
@synthesize addButton;
@synthesize assetsLibrary;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    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
{
    [assetArray release], assetArray = nil;
    [assetGroupURL release], assetGroupURL = nil;
    [assetGroupName release], assetGroupName = nil;
    [assetsLibrary release], assetsLibrary = nil;
    
    [super dealloc];
}

- (IBAction)addButtonTouched:(id)sender 
{    
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeCamera])
    {
        
        UIImagePickerController *ip = 
        [[UIImagePickerController alloc] init];
        
        [ip setSourceType:
         UIImagePickerControllerSourceTypeCamera];
        
        [ip setDelegate:self];
        
        [self presentViewController:ip 
                           animated:YES 
                         completion:nil];
        
        [ip release];
    }
    else
    {
        NSString *errMsg = @"Camera Not Available";
        
        UIAlertView* alertView = 
        [[UIAlertView alloc] initWithTitle:nil 
                                   message:errMsg 
                                  delegate:nil 
                         cancelButtonTitle:@"Dismiss" 
                         otherButtonTitles:nil];
        
        [alertView show];
        [alertView release];
    }
}

#pragma mark - Image Picker Controller Delegate

- (void)imagePickerController:(UIImagePickerController *)picker 
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *selectedImage = 
    [info objectForKey:UIImagePickerControllerEditedImage];
    
    if (!selectedImage) 
    {
        
        selectedImage = 
        [info objectForKey:UIImagePickerControllerOriginalImage];
        
    }
    
    UIImageWriteToSavedPhotosAlbum(selectedImage, self, 
     @selector(image:didFinishSavingWithError:contextInfo:), 
     NULL);
    
    [self dismissModalViewControllerAnimated:YES];    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)image:(UIImage *)image 
didFinishSavingWithError:(NSError *)error 
  contextInfo:(void *)contextInfo {
    
    if(error != nil)
    {
        NSLog(@"Error Saving:%@",[error localizedDescription]);
        return;
    }
    [self.assetArray removeAllObjects];
    [self retrieveAssetGroupByURL];
}

#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue 
                 sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"ViewAssetImage"])
	{
        NSInteger indexForAsset = [sender tag];
        
        ALAsset *selectedAsset =
        [assetArray objectAtIndex:indexForAsset];
        
        ICFAssetViewController *aVC = 
        segue.destinationViewController;
        
        ALAssetRepresentation *rep = 
        [selectedAsset defaultRepresentation];
        
        UIImage *img = 
        [UIImage imageWithCGImage:[rep fullScreenImage]];
        
        [aVC setAssetImage: img];
	}
}

#pragma mark - Table methods
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    NSInteger returnCount = 0;
    
    if (assetArray && ([assetArray count] > 0))
    {
        if ([assetArray count] % 4 == 0)
        {
            returnCount = ([assetArray count] / 4);
        }
        else
        {
            returnCount = ([assetArray count] / 4) + 1; 
        }
    }
    return returnCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = @"ICFAssetGroupTableCell";
    ICFAssetGroupTableCell *cell = (ICFAssetGroupTableCell *)
    [tableView dequeueReusableCellWithIdentifier:cellID];
    
    ALAsset *firstAsset = 
    [assetArray objectAtIndex:indexPath.row * 4];
    
    [cell.assetButton1 setImage:
     [UIImage imageWithCGImage:[firstAsset thumbnail]] 
                       forState:UIControlStateNormal];
    
    [cell.assetButton1 setTag:indexPath.row * 4];
    
    if (indexPath.row * 4 + 1 < [assetArray count])
    {
        ALAsset *secondAsset = 
        [assetArray objectAtIndex:indexPath.row * 4 + 1];
        
        [cell.assetButton2 setImage:
         [UIImage imageWithCGImage:[secondAsset thumbnail]]
                           forState:UIControlStateNormal];
        
        [cell.assetButton2 setTag:indexPath.row * 4 + 1];
        [cell.assetButton2 setEnabled:YES];
    }
    else
    {
        [cell.assetButton2 setImage:nil 
                           forState:UIControlStateNormal];
        
        [cell.assetButton2 setEnabled:NO];
    }
    
    if (indexPath.row * 4 + 2 < [assetArray count])
    {
        ALAsset *thirdAsset = 
        [assetArray objectAtIndex:indexPath.row * 4 + 2];
        
        [cell.assetButton3 setImage:
         [UIImage imageWithCGImage:[thirdAsset thumbnail]] 
                           forState:UIControlStateNormal];
        
        [cell.assetButton3 setTag:indexPath.row * 4 + 2];
        [cell.assetButton3 setEnabled:YES];
    }
    else
    {
        [cell.assetButton3 setImage:nil 
                           forState:UIControlStateNormal];
        
        [cell.assetButton3 setEnabled:NO];
    }
    
    if (indexPath.row * 4 + 3 < [assetArray count])
    {
        ALAsset *fourthAsset = 
        [assetArray objectAtIndex:indexPath.row * 4 + 3];
        
        [cell.assetButton4 setImage:
         [UIImage imageWithCGImage:[fourthAsset thumbnail]] 
                           forState:UIControlStateNormal];
        
        [cell.assetButton4 setTag:indexPath.row * 4 + 3];
        [cell.assetButton4 setEnabled:YES];
    }
    else
    {
        [cell.assetButton4 setImage:nil 
                           forState:UIControlStateNormal];
        
        [cell.assetButton4 setEnabled:NO];
    }
    
    return cell;
}

#pragma mark - Asset Methods

- (void)retrieveAssetGroupByURL 
{
    void (^retrieveGroupBlock)(ALAssetsGroup*) = 
    ^(ALAssetsGroup* group) 
    {
        if (group)
        {
            [self enumerateGroupAssetsForGroup:group];
        }
        else
        {
            NSLog(@"Error. Can't find group!");
        }
    };
    
    void (^handleAssetGroupErrorBlock)(NSError*) = 
    ^(NSError* error) 
    {
        NSString *errMsg = @"Error accessing group";
        
        UIAlertView* alertView = 
        [[UIAlertView alloc] initWithTitle:nil 
                                   message:errMsg 
                                  delegate:nil 
                         cancelButtonTitle:@"OK" 
                         otherButtonTitles:nil];
        
        [alertView show];
        [alertView release];
    };
    
    [self.assetsLibrary groupForURL:self.assetGroupURL
                        resultBlock:retrieveGroupBlock 
                       failureBlock:handleAssetGroupErrorBlock];
}

- (void)enumerateGroupAssetsForGroup:(ALAssetsGroup *)group 
{
    NSInteger lastIndex = [group numberOfAssets] - 1;

    void (^addAsset)(ALAsset*, NSUInteger, BOOL*) = 
    ^(ALAsset* result, NSUInteger index, BOOL* stop) 
    {
        if (result != nil)
        {
            [self.assetArray addObject:result];
        }
        
        if (index == lastIndex) {
            [self.assetTableView reloadData];
        }
    };
    
    [group enumerateAssetsUsingBlock:addAsset];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:self.assetGroupName];
    
    NSRange cameraRollLoc = 
    [self.assetGroupName rangeOfString:@"Camera Roll"];
    
    if (cameraRollLoc.location == NSNotFound)
    {
        [self.addButton setEnabled:NO];
    }
    
    ALAssetsLibrary *setupAssetsLibrary = 
    [[ALAssetsLibrary alloc] init];
    
    [self setAssetsLibrary:setupAssetsLibrary];
    [setupAssetsLibrary release];
    
    NSMutableArray *setupArray = [[NSMutableArray alloc] init];
    [self setAssetArray:setupArray];
    [setupArray release];

    [self retrieveAssetGroupByURL];
}

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

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

@end
