//
// AlphabeticalDataSourceProvider.m
// GoToBus
//
// Created by iphone development on 6/10/14.
//
//

#import "IMLocalizedIndexedCollation.h"
#import <BlocksKit/BlocksKit.h>

@interface IMLocalizedIndexedCollation ()
@property (nonatomic, strong) NSArray *sectionIndexTitles;
@property (nonatomic, strong) NSArray *sectionSortedArrays;
@end

@implementation IMLocalizedIndexedCollation

#pragma mark - Public

- (instancetype)initWithObjects:(NSArray *)objects sortedUsingBlock:(NSString * (^) (id obj))block {
	if (self = [self init]) {
		[self loadObjects:objects collationStringSelector:@selector(description) usingBlock:block];
	}
	return self;
}

- (instancetype)initWithObjects:(NSArray *)objects sortedUsingSelector:(SEL)selector {
	if (self = [self init]) {
		[self loadObjects:objects collationStringSelector:selector usingBlock:nil];
	}
	return self;
}

- (instancetype)initWithObjects:(NSArray *)objects {
	if (self = [self init]) {
		[self loadObjects:objects collationStringSelector:@selector(description) usingBlock:nil];
	}
	return self;
}

#pragma mark - Private

- (void)loadObjects:(NSArray *)objects collationStringSelector:(SEL)selector usingBlock:(NSString * (^) (id obj))block {
	UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
	NSMutableArray *objectArrays = [NSMutableArray array];
	for (int i = 0; i < indexedCollation.sectionIndexTitles.count; i++) {
		[objectArrays addObject:[NSMutableArray array]];
	}
	NSMutableArray *objectSortedArrays = [NSMutableArray array];
	if (block) {
		for (id object in objects) {
			NSInteger i = [indexedCollation sectionForObject:block(object) collationStringSelector:selector];
			[objectArrays[i] addObject:object];
		}
		for (int i = 0; i < indexedCollation.sectionIndexTitles.count; i++) {
			[objectSortedArrays addObject:[indexedCollation sortedArrayFromArray:[objectArrays[i] bk_map:block] collationStringSelector:selector]];
		}
	} else {
		for (id object in objects) {
			NSInteger i = [indexedCollation sectionForObject:object collationStringSelector:selector];
			[objectArrays[i] addObject:object];
		}
		for (int i = 0; i < indexedCollation.sectionIndexTitles.count; i++) {
			[objectSortedArrays addObject:[indexedCollation sortedArrayFromArray:objectArrays[i] collationStringSelector:selector]];
		}
	}
	NSMutableArray *newIndexTitles = [NSMutableArray array];
	NSMutableArray *newSortedArrays = [NSMutableArray array];
	for (int i = 0; i < indexedCollation.sectionIndexTitles.count; i++) {
		if ([objectSortedArrays[i] count] > 0) {
			[newIndexTitles addObject:indexedCollation.sectionIndexTitles[i]];
			[newSortedArrays addObject:objectSortedArrays[i]];
		}
	}
	self.sectionIndexTitles = [NSArray arrayWithArray:newIndexTitles];
	self.sectionSortedArrays = [NSArray arrayWithArray:newSortedArrays];
}

@end
