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

#import "PSFontSettingsViewController.h"

#define kMaxNumberOfFonts 300

@interface PSFontSettingsViewController () {
    NSString *_fontNames[kMaxNumberOfFonts];
    NSString *_displayNames[kMaxNumberOfFonts];
    UIFont *_fonts[kMaxNumberOfFonts];
    NSInteger _numberOfFonts;
    NSInteger _selectedIndex;
}

@end

@implementation PSFontSettingsViewController

- (id)initWithTextStyle:(UITextStyleSettings *)textStyle {
    if (self = [super init]) {
        _textStyle = textStyle;
        NSString *currentFontName = [_textStyle fontName];
        
        [self setTitle:LS(@"FONT")];
        
        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];
        NSArray *familyNames = [UIFont familyNames];
        
        for (NSString *familyName in familyNames) {
            NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
            const NSInteger numberOfNames = [fontNames count];
            const NSInteger numberOfAll = _numberOfFonts + numberOfNames;
            
            if (kMaxNumberOfFonts <= numberOfAll) {
                break;
            }
            
            for (NSInteger i = 0; i < numberOfNames; ++ i) {
                NSString *fontName = [fontNames objectAtIndex:i];
                NSArray *components = [fontName componentsSeparatedByString:@"-"];
                const NSInteger j = _numberOfFonts + i;
                
                _fontNames[j] = fontName;
                if ([components count] > 1) {
                    _displayNames[j] = [familyName stringByAppendingFormat:@" %@", [components objectAtIndex:1]];
                } else {
                    _displayNames[j] = familyName;
                }
                
                if ([currentFontName isEqualToString:fontName]) {
                    _selectedIndex = j;
                }
            }
            _numberOfFonts = numberOfAll;
        }
    }
    return self;
}

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

- (void)viewWillAppear:(BOOL)animated {
    if (_selectedIndex < _numberOfFonts) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectedIndex inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    }
}

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

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [_textStyle setFontName:_fontNames[_selectedIndex]];
}

- (void)releaseSubviews {
    _tableView = nil;
}

#pragma mark - UITableViewDataSource

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return _numberOfFonts;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {
    const NSInteger row = [indexPath row];
    static NSString *CellIdentifier = @"PSFontCell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (nil == cell) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
	}
    
    UILabel *textLabel = [cell textLabel];
    
    if (nil == _fonts[row]) {
        const CGFloat size = [_fontNames[row] isEqualToString:@"Zapfino"] ? 12 : 16;
        
        _fonts[row] = [UIFont fontWithName:_fontNames[row] size:size];
    }
    [textLabel setFont:_fonts[row]];
    [textLabel setText:_displayNames[row]];
    [cell setAccessoryType:(row == _selectedIndex ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone)];
    
	return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    const NSInteger row = [indexPath row];
    UITableViewCell *deselectedCell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_selectedIndex inSection:0]];
    UITableViewCell *selectedCell = [_tableView cellForRowAtIndexPath:indexPath];
    
    [deselectedCell setAccessoryType:UITableViewCellAccessoryNone];
    [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
    
    _selectedIndex = row;
    
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Action 

- (void)onDone {
    [_textStyle setFontName:_fontNames[_selectedIndex]];
    [_textStyle save];
    [[self navigationController] dismissViewControllerAnimated:YES completion:NULL];
}

@end
