//
// DropDownViewController.m
// IvyMedia
//
// Created by haibara on 9/13/14.
//
//

#import "DropDownViewController.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit.h>
#import <libextobjc/EXTScope.h>

@implementation DropDownItem

- (BOOL)isEqual:(id)object {
	if (self == object) {
		return YES;
	}
	if (![object isKindOfClass:self.class]) {
		return NO;
	}
    return [[BeanUtils describe:self] isEqualToDictionary:[BeanUtils describe:object]];
}

@end

@interface DropDownViewController ()

@property (nonatomic, strong) NSMutableArray *selectedItems;

@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) NSMutableArray *indexTitles;
@property (nonatomic, strong) NSMutableArray *sortedArrays;

@property (nonatomic, strong, readonly) NSArray *allItems;

@property (nonatomic, copy) void (^didDoneBlock) (NSArray *items);
@property (nonatomic, copy) void (^didCancelBlock) (void);

@end

@implementation DropDownViewController

- (instancetype)init {
	self = [super init];
	if (self) {
		self.indexTitles = [NSMutableArray array];
		self.sortedArrays = [NSMutableArray array];
		self.selectedItems = [NSMutableArray array];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	@weakify(self)
	if (self.didCancelBlock) {
		self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] im_initWithBarButtonSystemItem:UIBarButtonSystemItemCancel handler:^(UIBarButtonItem *barButtonItem) {
			@strongify(self)
			self.didCancelBlock();
		}];
	}
	if (self.didDoneBlock) {
		self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] im_initWithBarButtonSystemItem:UIBarButtonSystemItemDone handler:^(UIBarButtonItem *barButtonItem) {
			@strongify(self)
			self.didDoneBlock([NSArray arrayWithArray:self.selectedItems]);
		}];
	}

	[self buildCellDataSource];
}

#pragma mark - Public

- (void)setItemsWithValues:(NSArray *)values {
	NSMutableArray *array1 = [NSMutableArray array];
	for (NSString *value in values) {
		DropDownItem *item = [[DropDownItem alloc] init];
		item.label = value;
		item.value = value;
		[array1 addObject:item];
	}
	self.indexTitles = nil;
	self.sortedArrays = @[[NSArray arrayWithArray:array1]];
}

- (void)setItemsWithValues:(NSArray *)values andLabels:(NSArray *)labels {
	NSMutableArray *array1 = [NSMutableArray array];
	for (int i = 0; i < values.count; i++) {
		DropDownItem *item = [[DropDownItem alloc] init];
		item.label = labels[i];
		item.value = values[i];
		[array1 addObject:item];
	}
	self.indexTitles = nil;
	self.sortedArrays = @[[NSArray arrayWithArray:array1]];
}

- (void)addItemsWithValues:(NSArray *)values andLabels:(NSArray *)labels groupedTitle:(NSString *)title {
	NSMutableArray *array1 = [NSMutableArray array];
	for (int i = 0; i < values.count; i++) {
		DropDownItem *item = [[DropDownItem alloc] init];
		item.label = labels[i];
		item.value = values[i];
		[array1 addObject:item];
	}
	[self.indexTitles addObject:title];
	[self.sortedArrays addObject:[NSArray arrayWithArray:array1]];
}

- (void)selectValues:(NSArray *)values {
	NSArray *array2 = [values valueForKeyPath:@"description"];
	NSArray *array1 = [self.allItems bk_select:^BOOL (DropDownItem *item) {
		return [array2 containsObject:[item.value description]];
	}];
	self.selectedItems = [NSMutableArray arrayWithArray:array1];
}

#pragma mark - Property

- (NSArray *)allItems {
	return [self.sortedArrays valueForKeyPath:@"@unionOfArrays.self"];
}

#pragma mark - Action

- (void)changeItem:(DropDownItem *)item onTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	if ([self.selectedItems containsObject:item]) {
		[self.selectedItems removeObject:item];
	} else {
		[self.selectedItems addObject:item];
	}
	[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *arrays = [NSMutableArray array];
	@weakify(self)
	for (NSArray *items in self.sortedArrays) {
		NSMutableArray *array = [NSMutableArray array];
		for (DropDownItem *item in items) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			if ([item.label isKindOfClass:[NSAttributedString class]]) {
				data.attributedText = item.label;
			} else if ([item.label isKindOfClass:[NSString class]]) {
				data.text = item.label;
			}
			data.allowsTextLineWrapping = YES;
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				@strongify(self)
				if ([self.selectedItems containsObject:item]) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
				@strongify(self)
				return [NSString stringWithFormat:@"%d", [self.selectedItems containsObject:item]];
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self changeItem:item onTableView: tableView atIndexPath: indexPath];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

#pragma mark - Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return self.cellDataArrays.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.cellDataArrays[section] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if (self.indexTitles) {
		return self.indexTitles[section];
	}
	return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

@end
