//
//  PHGBasicFlowViewController.m
//  PhotoGallery
//
//  Created by Joe Keeley on 7/20/13.
//  Copyright (c) 2013 ICF. All rights reserved.
//

#import "PHGBasicFlowViewController.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import "PHGThumbCell.h"
#import "PHGSectionHeader.h"
#import "PHGSectionFooter.h"

NSString *kThumbCell = @"kThumbCell"; // UICollectionViewCell storyboard id
NSString *kSectionHeader = @"kSectionHeader"; //section header storyboard id
NSString *kSectionFooter = @"kSectionFooter"; //section header storyboard id

@interface PHGBasicFlowViewController ()
@property (nonatomic, strong) NSMutableArray *assetArray;
@property (nonatomic, strong) NSMutableArray *assetGroupArray;
@property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
@property (nonatomic, strong) UICollectionViewFlowLayout *pageLayout;
@end

@implementation PHGBasicFlowViewController

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

- (void)enumerateGroupAssetsForGroup:(ALAssetsGroup *)group
{
    NSInteger lastIndex = [group numberOfAssets];
    
    
    __block NSMutableArray *groupAssetArray = [[NSMutableArray alloc] init];
    
    void (^addAsset)(ALAsset*, NSUInteger, BOOL*) =
    ^(ALAsset* result, NSUInteger index, BOOL* stop)
    {
        if (result != nil)
        {
            [groupAssetArray addObject:result];
        }
        
        if (index == lastIndex) {
            [self.assetArray addObject:groupAssetArray];
        }
    };
    
    [group enumerateAssetsUsingBlock:addAsset];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.collectionView setAllowsMultipleSelection:YES];
    
    self.assetArray = [[NSMutableArray alloc] init];
    self.assetGroupArray = [[NSMutableArray alloc] init];
    self.assetsLibrary = [[ALAssetsLibrary alloc] init];
    
    [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
                                      usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                                          if (group) {
                                              NSString *sectionTitle = [NSString stringWithFormat:@"%@ - %d",[group valueForProperty:ALAssetsGroupPropertyName], [group numberOfAssets]];
                                              [self.assetGroupArray addObject:sectionTitle];
                                              [self enumerateGroupAssetsForGroup:group];
                                          }
                                          else
                                          {
                                              [self.collectionView reloadData];
                                          }
                                      }
                                    failureBlock:^(NSError *error){
                                    }
     ];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Collection View Data Source methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return [self.assetGroupArray count];
}

- (NSInteger)collectionView:(UICollectionView *)view
     numberOfItemsInSection:(NSInteger)section;
{
    NSArray *sectionAssets = self.assetArray[section];
    return [sectionAssets count];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *supplementaryView = nil;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        PHGSectionHeader *sectionHeader =
        [collectionView dequeueReusableSupplementaryViewOfKind:kind
        withReuseIdentifier:kSectionHeader forIndexPath:indexPath];
        
        [sectionHeader.headerLabel
         setText:self.assetGroupArray[indexPath.section]];
        
        supplementaryView = sectionHeader;
    }
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        PHGSectionFooter *sectionFooter = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kSectionFooter forIndexPath:indexPath];
        
        NSString *footerString = [NSString stringWithFormat:@"...koniec z %@",self.assetGroupArray[indexPath.section]];
        [sectionFooter.footerLabel setText:footerString];
        
        supplementaryView = sectionFooter;
    }
    
    return supplementaryView;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    PHGThumbCell *cell =
    [cv dequeueReusableCellWithReuseIdentifier:kThumbCell
                                  forIndexPath:indexPath];

    ALAsset *assetForPath =
    self.assetArray[indexPath.section][indexPath.row];
        
    UIImage *assetThumb =
    [UIImage imageWithCGImage:[assetForPath thumbnail]];

    [cell.thumbImageView setImage:assetThumb];

    return cell;
}

#pragma mark - Collection View Delegate methods

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Item selected at indexPath: %@",indexPath);
}

- (void)collectionView:(UICollectionView *)collectionView
didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Item deselected at indexPath: %@",indexPath);
}

#pragma mark - Action methods

- (IBAction)actionTapped:(id)sender
{
    NSString *message = nil;

    if ([self.collectionView.indexPathsForSelectedItems count] == 0)
    {
        message = @"Nie zaznaczono elementów.";
    }
    else if ([self.collectionView.indexPathsForSelectedItems count] == 1)
    {
        message = @"Zaznaczono jeden element.";
    }
    else if ([self.collectionView.indexPathsForSelectedItems count] > 1) {
        message = [NSString stringWithFormat:@"Zaznaczono %d elementów.",[self.collectionView.indexPathsForSelectedItems count]];
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Zaznaczone elementy" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

@end
