//
//  AddFolderViewController.m
//  OpenStack
//
//  Created by Mike Mayo on 1/4/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "AddFolderViewController.h"
#import "RSTextFieldCell.h"
#import "ActivityIndicatorView.h"
#import "UIViewController+Conveniences.h"
#import "OpenStackAccount.h"
#import "AccountManager.h"
#import "Container.h"
#import "Folder.h"
#import "StorageObject.h"
#import "FolderViewController.h"
#import "APICallback.h"


@implementation AddFolderViewController

@synthesize account, container, folder, folderViewController;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"Add Folder";
    [self addSaveButton];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [textField becomeFirstResponder];
}

#pragma mark -
#pragma mark Save Button

- (void)saveButtonPressed:(id)sender {    
    if (!saving) {        
        if ([textField.text isEqualToString:@""]) {
            [self alert:@"Folder Name Required" message:@"Please enter a folder name."];
        } else {
            [textField resignFirstResponder];
            NSString *objectName;
            BOOL objectNameHasTrailingSlash = [textField.text hasSuffix:@"/"];
            NSUInteger indexOfFirstSlash = [textField.text rangeOfString:@"/"].location;
            
            if ((!objectNameHasTrailingSlash && indexOfFirstSlash != NSNotFound) || 
                (objectNameHasTrailingSlash && indexOfFirstSlash < textField.text.length - 1)) {
                [self alert:@"Invalid folder name" message:@"'/' characters are only allowed at the end of folder names"];
                return;
            }
                
            if (folder && folder.name) {
                objectName = [NSString stringWithFormat:@"%@/%@", [folder fullPath], textField.text];
            } else {
                objectName = textField.text;
            }
            
            if ([folderViewController.folder.folders objectForKey:objectName] && !allowOverwrite) {
                NSString *alertMessage = [NSString stringWithFormat:@"An object with path '%@' in the container '%@' already exists, do you want to replace it?",objectName, folderViewController.container.name];
                NSString *alertTitle = @"Apply changes";
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertTitle
                                                                message:alertMessage
                                                               delegate:self
                                                      cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:@"OK", nil];
                [alert show];
                return;
            }

            NSString *activityMessage = @"Adding folder...";
            
            // figure out how many folders to create
            
            activityIndicatorView = [[ActivityIndicatorView alloc] initWithFrame:[ActivityIndicatorView frameForText:activityMessage] text:activityMessage];
            [activityIndicatorView addToView:self.view];
            
            // actually create the folders
            StorageObject *object = [[StorageObject alloc] init];
            object.name = object.fullPath = objectName;
            object.data = [NSData data];
            object.contentType = @"application/directory";

            [[self.account.manager writeObject:self.container object:object downloadProgressDelegate:nil]
             success:^(OpenStackRequest *request) {
                 Folder *newFolder = [[Folder alloc] init];
                 if (objectNameHasTrailingSlash)
                     object.name = [object.name substringToIndex:object.name.length - 1];
                 newFolder.name = [[object.name componentsSeparatedByString:@"/"] lastObject];
                 if (objectNameHasTrailingSlash)
                     newFolder.name = [newFolder.name stringByAppendingString:@"/"];
                 newFolder.parent = folder;
                 newFolder.sharing = folder.sharing;
                 BOOL currentFolderIsRoot;
                 if ([folderViewController.folder isEqual:container.rootFolder]) {
                     currentFolderIsRoot = YES;
                 }
                 [folder.folders setObject:newFolder forKey:newFolder.name];
                 [folderViewController.tableView reloadData];
                 if (currentFolderIsRoot) {
                     container.count += 1;
                     container.rootFolder = folder;
                     [self.account.containers setObject:container forKey:container.name];
                 }
                 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
                     [folderViewController setDetailViewController];
                 
                 allowOverwrite = NO;
                 [activityIndicatorView removeFromSuperviewAndRelease];
                 [self dismissModalViewControllerAnimated:YES];
                 [newFolder release];
                 [object release];
 
             }
             failure:^(OpenStackRequest *request) {
                 allowOverwrite = NO;
                 [activityIndicatorView removeFromSuperviewAndRelease];
                 [self alert:@"There was a problem creating this folder." request:request];
                 [object release];
             }];
        }
    }
}

#pragma mark -
#pragma mark Table view data source

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

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

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return @"If your folder name contains any forward slash characters, multiple folder objects will be created.";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"FolderNameCell";
    RSTextFieldCell *cell = (RSTextFieldCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[RSTextFieldCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        cell.modalPresentationStyle = UIModalPresentationFormSheet;
		textField = cell.textField;
        textField.delegate = self;
		textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }    
    cell.textLabel.text = @"Name";
    return cell;
}

#pragma mark - Alertview delegate

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


#pragma mark -
#pragma mark Text Field Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self saveButtonPressed:nil];
    return NO;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    [account release];
    [container release];
    [folder release];
    [folderViewController release];
    [super dealloc];
}

@end

