//
//  FSDirectoryNameViewController.m
//  Downloader
//
//  Created by LiDong on 13-3-13.
//  Copyright (c) 2013年 LiDong. All rights reserved.
//

#import "FSFileNameViewController.h"
#import "FSTextViewController.h"
#import "FSFileListViewController.h"

@interface FSFileNameViewController ()
- (void)onSave;
@end

@implementation FSFileNameViewController

@synthesize originalFileName = _originalFileName;
@synthesize directory = _directory;

- (id)initWithParentPath:(NSString *)parentPath {
    if (self = [super init]) {
        _parentPath = [parentPath copy];
        
        UINavigationItem *navigationItem = [self navigationItem];
        
        UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onCancel)];
        
        [navigationItem setLeftBarButtonItem:cancelItem];
        
        UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(onSave)];
        
        [saveItem setEnabled:NO];
        [navigationItem setRightBarButtonItem:saveItem];
        
        UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
        
        NSArray *toolbarItems = [[NSArray alloc] initWithObjects:flexibleItem, _rotationItem, nil];
        
        [self setToolbarItems:toolbarItems];
        
    }
    return self;
}

- (void)loadView {
    _contentView = [[UIView alloc] initWithFrame:CGRectPortraitScreen];
    [_contentView setBackgroundColor:UIColorTexturedBackground];
    [_contentView setUserInteractionEnabled:YES];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectZero];
    [_textField setDelegate:self];
    [_textField setBorderStyle:UITextBorderStyleRoundedRect];
    [_textField setKeyboardAppearance:UIKeyboardAppearanceDefault];
    [_textField setKeyboardType:UIKeyboardTypeDefault];
    [_textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [_textField setAutocorrectionType:UITextAutocorrectionTypeNo];
    [_textField setReturnKeyType:UIReturnKeyDone];
    [_textField setFont:UIFontBold16];
    [_textField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    
    [_contentView addSubview:_textField];
    
    [self setView:_contentView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (_originalFileName) {
        [_textField setText:_originalFileName];
        _canSave = NO;
    } else {
        if (_directory) {
            [_textField setText:@"Untitled"];
        } else {
            [_textField setText:@"Untitled.txt"];
        }
        _canSave = YES;
    }
    [[[self navigationItem] rightBarButtonItem] setEnabled:_canSave];
    [_textField becomeFirstResponder];
}

- (void)layoutWithContentSize:(const CGSize)contentSize {
    CGFloat x, w, gapY;
    
    if (contentSize.width < contentSize.height) {
        x = 15;
        w = contentSize.width - 30;
        gapY = (contentSize.height - 216 - 31) / 2.f;
    } else {
        x = 20;
        w = contentSize.width - 40;
        gapY = (contentSize.height - 162 - 31) / 2.f;
    }
    const CGRect inputFrame = { x, gapY, w, 31 };
    
    [_textField setFrame:inputFrame];
}

- (void)releaseSubviews {
    _contentView = nil;
    _textField = nil;
}

- (void)dealloc {
}

#pragma mark - UITextFieldDelegate

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

- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

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

- (void)textFieldDidEndEditing:(UITextField *)textField {
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = [textField text];
    const NSUInteger textLength = [text length];
    const NSUInteger newLength = [string length];
    
    _canSave = ((textLength + newLength) > range.length) ? YES : NO;
    
    if (_originalFileName && _canSave) {
        NSString *newText = [text stringByReplacingCharactersInRange:range withString:string];
        
        _canSave = ![_originalFileName isEqualToString:newText];
    }
    
    [[[self navigationItem] rightBarButtonItem] setEnabled:_canSave];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (_canSave) {
        [self onSave];
    }
    return NO;
}

#pragma - Action

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

- (void)doSave {
    FSFileListViewController *fileListControlelr = [FSFileListViewController currentFileListViewController];
    
    [fileListControlelr beginUpdate];
    
    NSString *newName = [_textField text];
    NSString *newPath = [_parentPath stringByAppendingPathComponent:newName];
    BOOL isNewTextFile = NO;
    
    if (_originalFileName) {
        NSString *oldPath = [_parentPath stringByAppendingPathComponent:_originalFileName];
        
        [theFileManager moveItemAtPath:oldPath toPath:newPath error:NULL];
    } else {
        if (_directory) {
            [theFileManager createDirectoryAtPath:newPath withIntermediateDirectories:NO attributes:nil error:NULL];
        } else {
            UITextStyleSettings *textStyle = [[UITextStyleSettings alloc] initWithPath:newPath];
            
            [theFileManager createFileAtPath:newPath contents:nil attributes:[textStyle fileAttributes]];
            isNewTextFile = YES;
        }
    }
    
    [fileListControlelr endUpdate];
    
    UINavigationController *navigationController = [self navigationController];
    
    if (isNewTextFile) {
        FSTextViewController *viewController = [[FSTextViewController alloc] initWithPath:newPath];
        NSArray *viewControllers = [[NSArray alloc] initWithObjects:viewController, nil];
        
        [viewController setEditing:YES animated:NO];
        [navigationController setViewControllers:viewControllers animated:YES];
    } else {
        [navigationController dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (void)onSave {
    NSString *newName = [_textField text];
    
    if (!_directory && ![newName hasSuffix:@".txt"]) {
        newName = [newName stringByAppendingPathExtension:@"txt"];
        [_textField setText:newName];
    }
    
    NSString *newPath = [_parentPath stringByAppendingPathComponent:newName];
    
    if ([theFileManager fileExistsAtPath:newPath]) {
        NSString *message = [[NSString alloc] initWithFormat:LS(@"ITEM_EXISTS_FORMATTER"), newName];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:LS(@"SAVE_NAME") message:message delegate:self cancelButtonTitle:LS(@"CANCEL") otherButtonTitles:LS(@"REPLACE"), nil];
        
        [alert show];
    } else {
        [self doSave];
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (1 == buttonIndex) {
        [self doSave];
    }
}

#pragma mark -

- (void)setOriginalFileName:(NSString *)fileName {
    NSString *path = [_parentPath stringByAppendingPathComponent:fileName];
    
    if ([theFileManager fileExistsAtPath:path]) {
        _originalFileName = [fileName copy];
    } else {
        _originalFileName = nil;
    }
}

@end
