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

#import "PSSettingViewController.h"
#import "PSSortingViewController.h"
#import "PSTextSettingsViewController.h"
#import "UISettings.h"

#define kNumberOfSections 4

@interface PSSettingViewController () {
    NSInteger _numberOfRows[kNumberOfSections];
    NSString *_sectionTitles[kNumberOfSections];
}

@end

@implementation PSSettingViewController

- (id)init {
    if (self = [super init]) {
        [self setTitle:LS(@"SETTINGS")];
        
        _numberOfRows[0] = 1;
        _numberOfRows[1] = 2;
        _numberOfRows[2] = 1;
        _numberOfRows[3] = 1;
        _sectionTitles[0] = LS(@"SCREEN_ORIENTATION");
        _sectionTitles[1] = LS(@"FILE_BROWSER");
        _sectionTitles[2] = LS(@"VIEWING_FILES");
        _sectionTitles[3] = LS(@"WEB_BROWSER");
        
        UINavigationItem *navigationItem = [self navigationItem];
        UIBarButtonItem *homeItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bar/home.png"] style:UIBarButtonItemStyleDone target:self action:@selector(onHome)];
        UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onDone)];
        
        [navigationItem setLeftBarButtonItem:homeItem];
        [navigationItem setRightBarButtonItem:doneItem];
        _keyboardHeight = 216.f;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

- (void)loadView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectPortraitLongVC style:UITableViewStyleGrouped];
    [_tableView setDataSource:self];
    [_tableView setDelegate:self];
    [_tableView setRowHeight:44];
    
    _orientationSwitch = [[UISwitch alloc] initWithFrame:RECT(0, 0, 80, 32)];
    [_orientationSwitch setOn:UISettingsOrientationIsLocked()];
    [_orientationSwitch addTarget:self action:@selector(onInvertRotationLock) forControlEvents:UIControlEventValueChanged];
    
    _extensionsSwitch = [[UISwitch alloc] initWithFrame:RECT(0, 0, 80, 32)];
    [_extensionsSwitch setOn:UISettingsShowFileExtensions()];
    [_extensionsSwitch addTarget:self action:@selector(onInvertShowFileExtension) forControlEvents:UIControlEventValueChanged];
    
    _urlTextField = [[UITextField alloc] initWithFrame:CGRectZero];
    
    [_urlTextField setDelegate:self];
    [_urlTextField setBorderStyle:UITextBorderStyleNone];
    [_urlTextField setKeyboardAppearance:UIKeyboardAppearanceDefault];
    [_urlTextField setKeyboardType:UIKeyboardTypeURL];
    [_urlTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [_urlTextField setAutocorrectionType:UITextAutocorrectionTypeNo];
    [_urlTextField setReturnKeyType:UIReturnKeyDone];
    [_urlTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [_urlTextField setTextAlignment:NSTextAlignmentRight];
    [_urlTextField setTextColor:UIColorDarkCyan];
    [_urlTextField setFont:UIFontNormal14];
    [_urlTextField setText:UISettingsGetHomePage()];
    
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    
    [gestureRecognizer setCancelsTouchesInView:NO];
    [_tableView addGestureRecognizer:gestureRecognizer];
    [[self navigationController] setToolbarHidden:YES];
    
    [self setView:_tableView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSIndexPath *selectedIndexPath = [_tableView indexPathForSelectedRow];
    
    if (selectedIndexPath) {
        [_tableView deselectRowAtIndexPath:selectedIndexPath animated:YES];
    }
}

- (void)releaseSubviews {
    _tableView = nil;
    _orientationSwitch = nil;
    _extensionsSwitch = nil;
    _urlTextField = nil;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#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 {
	return _sectionTitles[section];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {
    const NSInteger section = [indexPath section];
    const NSInteger row = [indexPath row];
    NSString *CellIdentifier = [[NSString alloc] initWithFormat:@"Cell-%d-%d", section, row];
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (nil == cell) {
        NSString *text = nil;
        UITableViewCellSelectionStyle selectionStyle = UITableViewCellSelectionStyleNone;
        UITableViewCellAccessoryType accessoryType = UITableViewCellAccessoryNone;
        
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        if (0 == section) {
            text = LS(@"LOCK_ORIENTATION");
            [cell setAccessoryView:_orientationSwitch];
        } else if (1 == section) {
            if (0 == row) {
                text = LS(@"SHOW_EXTENSIONS");
                [cell setAccessoryView:_extensionsSwitch];
            } else if (1 == row) {
                text = LS(@"SORTING_FILES");
                accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                selectionStyle = UITableViewCellSelectionStyleGray;
            } else {
            }
        } else if (2 == section) {
            if (0 == row) {
                text = LS(@"VIEWING_TXT_FILES");
                accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                selectionStyle = UITableViewCellSelectionStyleGray;
            }
        } else {
            text = LS(@"HOME_PAGE");
            [cell addSubview:_urlTextField];
        }
        
        UILabel *textLabel = [cell textLabel];
        
        [textLabel setFont:UIFontBold16];
        [textLabel setText:text];
        [cell setSelectionStyle:selectionStyle];
        [cell setAccessoryType:accessoryType];
	}
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    const NSInteger section = [indexPath section];
    const NSInteger row = [indexPath row];
    UIViewController *viewController = nil;
    
    if (1 == section) {
        if (1 == row) {
            viewController = [[PSSortingViewController alloc] init];
        }
    } else if (2 == section) {
        if (0 == row) {
            viewController = [[PSTextSettingsViewController alloc] init];
        }
    }
    if (viewController) {
        [[self navigationController] pushViewController:viewController animated:YES];
        }
}

#pragma mark -

- (void)layoutWithContentSize:(const CGSize)contentSize {
    CGRect viewFrame = { CGPointZero, contentSize };
    CGRect textFrame;
    
    if (contentSize.width < contentSize.height) {
        viewFrame.origin.y = 64;
        textFrame = RECT(contentSize.width - 180 - 5, 0, 180, 44);
    } else {
        viewFrame.origin.y = 52;
        textFrame = RECT(contentSize.width - 340 - 5, 0, 340, 44);
    }
    
    if (_editing) {
        viewFrame.size.height -= _keyboardHeight;
    }
    
    [_tableView setFrame:viewFrame];
    [_urlTextField setFrame:textFrame];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    _editing = YES;
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    CGRect viewFrame = [_tableView frame];
    
    viewFrame.size.height -= _keyboardHeight;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25f];
    [_tableView setFrame:viewFrame];
    [UIView commitAnimations];
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    _editing = NO;
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    const CGPoint contentOffset = [_tableView contentOffset];
    CGRect viewFrame = [_tableView frame];
    
    viewFrame.size.height += _keyboardHeight;
    
    [_tableView setFrame:viewFrame];
    [_tableView setContentOffset:contentOffset];
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Action

- (void)handleSingleTap:(UITapGestureRecognizer *)sender {
    [_urlTextField resignFirstResponder];
}

- (void)onHome {
    UISettingsSetHomePage([_urlTextField text]);
    [[self navigationController] dismissViewControllerAnimated:YES completion:NULL];
}

- (void)onDone {
    UISettingsSetHomePage([_urlTextField text]);
    [[self navigationController] dismissViewControllerAnimated:YES completion:NULL];
}

- (void)onInvertShowFileExtension {
    UISettingsInvertShowFileExtensions();
}

#pragma mark - Notification

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSNumber *rectNumber = [userInfo valueForKey:@"UIKeyboardBoundsUserInfoKey"];
    
    if (rectNumber) {
        const CGFloat newHeight = rectNumber.CGRectValue.size.height;
        
        if (fabs(newHeight - _keyboardHeight) >= 0.5f) {
            _keyboardHeight = newHeight;
            if (_editing) {
                const CGPoint contentOffset = [_tableView contentOffset];
                
                [self layoutWithContentSize:self.viewIfLoaded.bounds.size];
                [_tableView setContentOffset:contentOffset];
                [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
        }
    }
}

@end
