//
//  FSSortSettingsViewController.m
//  iFileReader
//
//  Created by LiDong on 13-4-6.
//  Copyright (c) 2013年 LiDong. All rights reserved.
//

#import "PSSortingViewController.h"
#import "FSFileListViewController.h"
#import "UISettings.h"

#define kNumberOfSections 2

@interface PSSortingViewController () {
    NSInteger _numberOfRows[kNumberOfSections];
    NSString *_sectionTitles[kNumberOfSections];
    NSString *_modeStrings[4];
    NSString *_orderStrings[2];
}

- (BOOL)saveSettings;

@end

@implementation PSSortingViewController

- (void)loadData {
    [self setTitle:LS(@"SORTING_FILES")];
    
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onDone)];
    
    [[self navigationItem] setRightBarButtonItem:doneItem];
    
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
    NSArray *toolbarItems = [[NSArray alloc] initWithObjects:flexibleItem, _rotationItem, nil];
    
    [self setToolbarItems:toolbarItems];
    _numberOfRows[0] = 4;
    _numberOfRows[1] = 2;
    _sectionTitles[0] = LS(@"FSSortingMode");
    _sectionTitles[1] = LS(@"FSSortingOrder");
    _modeStrings[SORT_BY_NAME] = LS(@"SORT_BY_NAME");
    _modeStrings[SORT_BY_DATE] = LS(@"SORT_BY_DATE");
    _modeStrings[SORT_BY_KIND] = LS(@"SORT_BY_KIND");
    _modeStrings[SORT_BY_SIZE] = LS(@"SORT_BY_SIZE");
    _orderStrings[0] = LS(@"ASCENDING");
    _orderStrings[1] = LS(@"DESCENDING");
    
    _originalModeIndex = UISettingsGetSortingMode();
    _selectedModeIndex = _originalModeIndex;
    _originalOrderIndex = (NSOrderedDescending == UISettingsGetSortingOrder()) ? 1 : 0;
    _selectedOrderIndex = _originalOrderIndex;
}

- (id)init {
    if (self = [super init]) {
        [self loadData];
        _shouldSave = YES;
    }
    return self;
}

- (id)initForFileSystem {
    if (self = [super init]) {
        [self loadData];
        
        UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onCancel)];
        
        [[self navigationItem] setLeftBarButtonItem:cancelItem];
        }
    return self;
}

- (void)loadView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectPortraitShortVC style:UITableViewStyleGrouped];
    [_tableView setDataSource:self];
    [_tableView setDelegate:self];
    [_tableView setRowHeight:44];
    
    [self setView:_tableView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_shouldSave && [self saveSettings] && _shouldNotify) {
        [[FSFileListViewController currentFileListViewController] refresh];
    }
}

- (void)releaseSubviews {
    _tableView = nil;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return kNumberOfSections;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return _numberOfRows[section];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	// Section title is the region name
	return _sectionTitles[section];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {
    UILabel *textLabel = nil;
	static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (nil == cell) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        textLabel = [cell textLabel];
        
        [textLabel setFont:UIFontBold16];
	} else {
        textLabel = [cell textLabel];
    }
    
    const NSInteger row = [indexPath row];
    NSString *text = nil;
    NSInteger selectedRow = -1;
    
    if (0 == [indexPath section]) {
        text = _modeStrings[row];
        selectedRow = _selectedModeIndex;
    } else {
        text = _orderStrings[row];
        selectedRow = _selectedOrderIndex;
    }
    
    [textLabel setText:text];
    [cell setAccessoryType:((row == selectedRow) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone)];
	
	return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    const NSInteger section = [indexPath section];
    const NSInteger row = [indexPath row];
    NSInteger delectedIndex = -1;
    
    if (0 == section) {
        if (row != _selectedModeIndex) {
            delectedIndex = _selectedModeIndex;
            _selectedModeIndex = row;
        }
    } else {
        if (row != _selectedOrderIndex) {
            delectedIndex = _selectedOrderIndex;
            _selectedOrderIndex = row;
        }
    }
    
    if (-1 != delectedIndex) {
        UITableViewCell *deselectedCell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:delectedIndex inSection:section]];
        UITableViewCell *selectedCell = [_tableView cellForRowAtIndexPath:indexPath];
        
        [deselectedCell setAccessoryType:UITableViewCellAccessoryNone];
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
    }
    
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Action 

- (void)onCancel {
    [[self navigationController] dismissViewControllerAnimated:YES completion:NULL];
}

- (void)onDone {
    _shouldSave = YES;
    _shouldNotify = YES;
    [[self navigationController] dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - 

- (BOOL)saveSettings {
    BOOL needSave = NO;
    
    if (_originalModeIndex != _selectedModeIndex) {
        _originalModeIndex = _selectedModeIndex;
        needSave = YES;
    }
    if (_originalOrderIndex != _selectedOrderIndex) {
        _originalOrderIndex = _selectedOrderIndex;
        needSave = YES;
    }
    if (needSave) {
        UISettingsSetSortingData(_selectedModeIndex, ((0 == _selectedOrderIndex) ? NSOrderedAscending : NSOrderedDescending));
    }
    return needSave;
}

@end
