//
//  RootViewController.m
//  FilesystemExplorer
//
//  Created by Chris Adamson on 11/4/08.
//  Copyright Subsequently and Furthermore, Inc. 2008. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//

#import "DirectoryViewController.h"
#import "FilesystemExplorerAppDelegate.h"
#import "FileOverviewViewController.h"
#import "CreateDirectoryViewController.h"
#import "CreateFileViewController.h"



@implementation DirectoryViewController

// providing our own property implementation for directoryPath 
// so we can update the table when its set

//START:code.FilesystemExplorer.directorypathpropertyimpl
-(NSString*) directoryPath {
	return directoryPath;
}

-(void) setDirectoryPath: (NSString*) p {
	[p retain];
	[directoryPath release];
	directoryPath = p;
	[self loadDirectoryContents];
	// also set title of nav controller with last path element
	NSString *pathTitle= [directoryPath lastPathComponent];
	self.title = pathTitle;
}
//END:code.FilesystemExplorer.directorypathpropertyimpl


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


//START:code.FilesystemExplorer.getDirectoryTableRowCount
- (NSInteger)tableView:(UITableView *)tableView
		numberOfRowsInSection:(NSInteger)section {
	return [directoryContents count];
}
//END:code.FilesystemExplorer.getDirectoryTableRowCount

//START:code.FilesystemExplorer.getDirectoryTableRowCell
- (UITableViewCell *)tableView:(UITableView *)table
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"DirectoryViewCell";
	UITableViewCell *cell =
		[table dequeueReusableCellWithIdentifier:
		CellIdentifier];
	if (cell == nil) {
        cell = [[[UITableViewCell alloc]
			initWithStyle:UITableViewCellStyleDefault
			reuseIdentifier:CellIdentifier] autorelease];
	}
//START_HIGHLIGHT
	cell.textLabel.text = (NSString*)
		[directoryContents objectAtIndex: indexPath.row];
//END_HIGHLIGHT
	return cell;
}
//END:code.FilesystemExplorer.getDirectoryTableRowCell


//START:code.FilesystemExplorer.handledeleteswipe
- (void)tableView:(UITableView *)tableView 
		commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
		forRowAtIndexPath:(NSIndexPath *)indexPath {
	// handle a delete swipe
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		NSString *selectedFile = (NSString*)
			[directoryContents objectAtIndex: indexPath.row];
		NSString *selectedPath =
			[directoryPath stringByAppendingPathComponent:
				selectedFile];
		BOOL canWrite =
			[[NSFileManager defaultManager]
				isWritableFileAtPath: selectedPath];
		if (! canWrite) {
			// show a UIAlert saying path isn't writable
//END:code.FilesystemExplorer.handledeleteswipe
			NSString *alertMessage = [NSString stringWithFormat: @"Cannot delete %@", selectedFile];
			UIAlertView *cantWriteAlert =
				[[UIAlertView alloc] initWithTitle:@"Not permitted:"
						message:alertMessage
						delegate:nil
						cancelButtonTitle:@"OK"
						otherButtonTitles:nil];
			[cantWriteAlert show];
			[cantWriteAlert release];
			return;
		}
		
		// try to delete
//START:code.FilesystemExplorer.deletefile
		NSError *err = nil;
		if (! [[NSFileManager defaultManager] removeItemAtPath: selectedPath error:&err]) {
			// show a UIAlert saying cannot delete
//END:code.FilesystemExplorer.deletefile
			NSString *alertMessage = (err == noErr) ?
				[NSString stringWithFormat: @"Cannot delete %@", selectedFile] :
				[NSString stringWithFormat: @"Cannot delete %@, %@",
						selectedFile, [err localizedDescription]];
			UIAlertView *cantDeleteAlert =
				[[UIAlertView alloc] initWithTitle:@"Can't delete:"
						message:alertMessage
						delegate:nil
						cancelButtonTitle:@"OK"
						otherButtonTitles:nil];
			[cantDeleteAlert show];
			[cantDeleteAlert release];
			return;
		}
		
		// refresh display
//START:code.FilesystemExplorer.refreshafterdelete
		NSArray *deletedPaths = [NSArray arrayWithObject: indexPath];
		[self loadDirectoryContents];
		[self.tableView deleteRowsAtIndexPaths: deletedPaths
			withRowAnimation: YES];
	}
}
//END:code.FilesystemExplorer.refreshafterdelete

// START:code.FilesystemExplorer.navToDirectory
- (void)tableView:(UITableView *)tableView
		didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString *selectedFile = (NSString*)
	[directoryContents objectAtIndex: indexPath.row];
	BOOL isDir;
	NSString *selectedPath =
	[directoryPath stringByAppendingPathComponent: selectedFile];
	if ([[NSFileManager defaultManager]
		 fileExistsAtPath:selectedPath isDirectory:&isDir] && isDir) {
		DirectoryViewController *directoryViewController =
			[[DirectoryViewController alloc]
				initWithNibName: @"DirectoryViewController"
				bundle:nil];
		[[self navigationController]
			pushViewController:directoryViewController animated:YES];
		directoryViewController.directoryPath = selectedPath;
		[directoryViewController release];
	}
	// END:code.FilesystemExplorer.navToDirectory
	// START:code.FilesystemExplorer.navToFile
	else {
		FileOverviewViewController *fileOverviewViewController =
			[[FileOverviewViewController alloc]
				initWithNibName: @"FileOverviewView"
				bundle:nil];
		[[self navigationController]
			pushViewController:fileOverviewViewController animated:YES];
		fileOverviewViewController.filePath = selectedPath;
		[fileOverviewViewController release];
	}
}
// END:code.FilesystemExplorer.navToFile


/*
*/
// START:code.FilesystemExplorer.directoryviewdidload
- (void)viewDidLoad {
    [super viewDidLoad];
	UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] 
		initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
		target:self
		action:@selector(showAddOptions)] autorelease];
	 self.navigationItem.rightBarButtonItem = addButton;
}
// END:code.FilesystemExplorer.directoryviewdidload


// START:code.FilesystemExplorer.showAddOptions
-(void) showAddOptions {
	NSString *sheetTitle = [[NSString alloc]
			initWithFormat: @"Edit \"%@\"",
			[directoryPath lastPathComponent]];
	UIActionSheet *actionSheet = [[UIActionSheet alloc]
			initWithTitle: sheetTitle
			delegate: self
			cancelButtonTitle: @"Cancel"
			destructiveButtonTitle: NULL
			otherButtonTitles: @"New File", @"New Directory", NULL];
	[actionSheet showInView: self.view];
	[sheetTitle release];
	[actionSheet release];
}
// END:code.FilesystemExplorer.showAddOptions

//START:code.FilesystemExplorer.actionsheetclickedbuttonatindex
- (void)actionSheet:(UIActionSheet *)actionSheet
		clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) 
		[self createNewFile];
	else if (buttonIndex == 1)
		[self createNewDirectory];
}
//END:code.FilesystemExplorer.actionsheetclickedbuttonatindex

/*
// Override to support editing the list
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support conditional editing of the list
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support rearranging the list
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the list
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
}
*/

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
	[directoryContents release];
	[directoryPath release];
}


//START:code.FilesystemExplorer.createnewfile
- (void)createNewFile  {
	BOOL canWrite = [[NSFileManager defaultManager]
						isWritableFileAtPath: self.directoryPath];
	if (! canWrite) {
		NSString *alertMessage = @"Cannot write to this directory";
		UIAlertView *cantWriteAlert =
		[[UIAlertView alloc] initWithTitle:@"Not permitted:"
						message:alertMessage delegate:nil
						cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[cantWriteAlert show];
		[cantWriteAlert release];
		return;
	}
	// present modal view controller to name file
	CreateFileViewController *createFileViewController =
		[[CreateFileViewController alloc]
			initWithNibName: @"CreateFileView"
			bundle:nil];
	createFileViewController.parentDirectoryPath = directoryPath;
	createFileViewController.directoryViewController = self;
	createFileViewController.title = @"Create file";
	[[self navigationController]
		pushViewController:createFileViewController animated:YES];
	[createFileViewController release];
}
//END:code.FilesystemExplorer.createnewfile

//START:code.FilesystemExplorer.createnewdirectory
- (void)createNewDirectory {
	BOOL canWrite = [[NSFileManager defaultManager]
			isWritableFileAtPath: self.directoryPath];
	if (! canWrite) {
		NSString *alertMessage = @"Cannot write to this directory";
		UIAlertView *cantWriteAlert =
			[[UIAlertView alloc] initWithTitle:@"Not permitted:"
				message:alertMessage
				delegate:nil
				cancelButtonTitle:@"OK"
				otherButtonTitles:nil];
		[cantWriteAlert show];
		[cantWriteAlert release];
		return;
	}
	CreateDirectoryViewController *createDirectoryViewController =
		[[CreateDirectoryViewController alloc]
			initWithNibName: @"CreateDirectoryView"
			bundle:nil];
	createDirectoryViewController.parentDirectoryPath = directoryPath;
	createDirectoryViewController.directoryViewController = self;
	createDirectoryViewController.title = @"Create directory";
	[[self navigationController]
		pushViewController:createDirectoryViewController animated:YES];
	[createDirectoryViewController release];
}
//END:code.FilesystemExplorer.createnewdirectory

 
//START:code.FilesystemExplorer.loadDirectoryContents
- (void) loadDirectoryContents {
	[directoryContents release];
	directoryContents = [[NSFileManager defaultManager]
		directoryContentsAtPath: directoryPath];
	[directoryContents retain];
}
//END:code.FilesystemExplorer.loadDirectoryContents


@end

