//
//  StudentTableViewController.m
//  StudentManager
//
//  Created by Rich on 2/9/11.
//  Copyright 2011 Swarthmore College. All rights reserved.
//

#import "StudentTableViewController.h"


@implementation StudentTableViewController

@synthesize students;
@synthesize detailViewController;
@synthesize selectedIndexPath;

#pragma mark -
#pragma mark ViewController Properties

- (StudentDetailViewController *)detailViewController
{
	if (!detailViewController) {
		detailViewController = [[StudentDetailViewController alloc] init];
	}
	return detailViewController;
}


#pragma mark -
#pragma mark Model

- (NSString *)studentDataPath
{
	NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	NSString *filePath = [docPath stringByAppendingPathComponent:@"students.data"];
	return filePath;
}


- (NSMutableArray *)arrayWithFakeData
{
	NSMutableArray *roster = [NSMutableArray arrayWithObjects:
							  [Student studentWithName:@"Rich" deptMajor:@"Computer Science" gradyear:1993],
							  [Student studentWithName:@"Andy" deptMajor:@"Physics" gradyear:1999],
							  [Student studentWithName:@"Lisa" deptMajor:@"Math" gradyear:1985],
							  [Student studentWithName:@"James" deptMajor:@"Physics" gradyear:2011],
							  [Student studentWithName:@"Ashley" deptMajor:@"Computer Science" gradyear:2011],
							  [Student studentWithName:@"Neil" deptMajor:@"Chemistry" gradyear:2012],
							  [Student studentWithName:@"Josh" deptMajor:@"Undeclared" gradyear:2013],
							  [Student studentWithName:@"Sarah" deptMajor:@"Computer Science" gradyear:2012],
							  [Student studentWithName:@"Doug" deptMajor:@"Computer Science" gradyear:2011],
							  [Student studentWithName:@"Catie" deptMajor:@"Undeclared" gradyear:2013],
							  nil];
	
	return roster;
}



- (void)saveData
{
	NSString *filePath = [self studentDataPath];
	BOOL success = [NSKeyedArchiver archiveRootObject:self.students toFile:filePath];
	if (!success) {
		NSLog(@"Error saving data!");
	}
}

- (NSMutableArray *)students
{
	if (!students) {
		BOOL useFakeData = YES;
		
		NSString *filePath = [self studentDataPath];
		NSMutableArray *loadStudents = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
		if (!loadStudents) {
			if (useFakeData) {
				loadStudents = [self arrayWithFakeData]; 
			} else {
				loadStudents = [NSMutableArray array]; //an empty autoreleased array
			}
		}
		self.students = loadStudents;
	}
	return students;
}



#pragma mark -
#pragma mark Initialization


- (id)initWithStyle:(UITableViewStyle)style {
    return [self init];
}


- (id)init
{
	//Call the super class' designated initializer
	if (self = [super initWithStyle:UITableViewStyleGrouped]) {

		self.navigationItem.leftBarButtonItem = self.editButtonItem;

		UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
																			 target:self 
																			 action:@selector(addPressed:)];
		self.navigationItem.rightBarButtonItem = bbi;
		[bbi release];
		
		self.title = @"Students";
		
		self.detailViewController.editStudent = [self.students objectAtIndex:0];
		self.selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];

	}
	
	return self;
}

#pragma mark -
#pragma mark View lifecycle

/*
- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	[self.students sortUsingSelector:@selector(compare:)];
	[self.tableView reloadData];
	[self.tableView selectRowAtIndexPath:self.selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];

}

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

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES;
}

#pragma mark -
#pragma mark Target-Action


- (void)addPressed:(id)sender
{
	Student *newStudent = [[Student alloc] init];
	[self.students addObject:newStudent];

	NSIndexPath *ip = [NSIndexPath indexPathForRow:self.students.count-1 inSection:0];
    [self tableView:self.tableView didSelectRowAtIndexPath:ip];
}



#pragma mark -
#pragma mark Table view data source
/*
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return <#number of sections#>;
}
*/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.students.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"StudentTableViewCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    } 
	
    Student *student = [self.students objectAtIndex:indexPath.row];
	cell.textLabel.text = student.description;
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (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 editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
		[self.students removeObjectAtIndex:indexPath.row];
		
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else 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 rearranging the table view.
- (void)  tableView:(UITableView *)tableView 
 moveRowAtIndexPath:(NSIndexPath *)fromIndexPath 
		toIndexPath:(NSIndexPath *)toIndexPath {
	Student *s = [students objectAtIndex:fromIndexPath.row];
	[s retain];
	
	[students removeObjectAtIndex:fromIndexPath.row];
	[students insertObject:s atIndex:toIndexPath.row];
	[s release];
}
*/


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

- (void)studentEditedForStudentDetailViewContollerDelegate:(StudentDetailViewController *)sender
{
	[self.students sortUsingSelector:@selector(compare:)];
	[self.tableView reloadData];
	//[self.tableView selectRowAtIndexPath:self.selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
}



#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	self.selectedIndexPath = indexPath;
	self.detailViewController.editStudent = [self.students objectAtIndex:indexPath.row];
	if (!self.detailViewController.view.window) {
		[self.navigationController pushViewController:self.detailViewController animated:YES];
	}

}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


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


@end

