// // EspagramLessonViewController.m // Espagram // // Created by Abel Fokkinga on 11/12/12. // Copyright (c) 2012 Abel Fokkinga. All rights reserved. // #import "EspagramLessonViewController.h" #import "Lesson+Create.h" #import "Lesson+Conjugator.h" #import "EspagramTestViewController.h" @interface EspagramLessonViewController () @end @implementation EspagramLessonViewController @synthesize lessonsDatabase = _lessonsDatabase; @synthesize conjugator = _conjugator; @synthesize tense = _tense; - (IBAction)addLessonButtonPressed:(id)sender { [self performSegueWithIdentifier:@"Add new Lesson" sender:self]; } - (void) addLesson:(NSString*)title withDescription:(NSString*) subTitle { NSLog(@"Need to dismiss modal view controller"); [[self presentedViewController] dismissViewControllerAnimated:TRUE completion:^{ NSLog(@"View controller dismissed"); }]; NSLog(@"database %@, context %@", self.lessonsDatabase,[self.lessonsDatabase managedObjectContext]); [Lesson addLessonWithTitle:title andSubTitle:subTitle inTense:self.tense conjugatedBy:self.conjugator inManagedObjectContext:[self.lessonsDatabase managedObjectContext]]; [self.lessonsDatabase saveToURL:self.lessonsDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL]; } - (void) cancelLesson{ NSLog(@"Cancel pressed, need to dismiss modal view controller"); [[self presentedViewController] dismissViewControllerAnimated:TRUE completion:^{ NSLog(@"View controller dismissed"); }]; } #pragma mark - View lifecycle - (void) setupFetchedResultsController{ NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Lesson"]; self.debug = TRUE; // Where clause request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:[NSPredicate predicateWithFormat:@"tense = %@", self.tense.tense], [NSPredicate predicateWithFormat:@"conjugator = %@", [self.conjugator description]],nil]]; request.sortDescriptors = [[NSArray alloc] initWithObjects:[[NSSortDescriptor alloc] initWithKey:@"title" ascending:TRUE], nil]; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.lessonsDatabase.managedObjectContext sectionNameKeyPath:nil cacheName:nil]; } - (void) createDocument { [self.lessonsDatabase saveToURL:self.lessonsDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL succes){ NSLog(@"Created lessons database"); }]; } - (void) useDocument { if (![[NSFileManager defaultManager] fileExistsAtPath:[self.lessonsDatabase.fileURL path]]) { [self createDocument]; [self fetchedResultsController]; } else if (self.lessonsDatabase.documentState == UIDocumentStateClosed){ [self.lessonsDatabase openWithCompletionHandler:^(BOOL succes){ NSLog(@"Opened lessons database"); [self setupFetchedResultsController]; }]; } else if (self.lessonsDatabase.documentState == UIDocumentStateNormal) { [self setupFetchedResultsController]; } } - (void) setLessonsDatabase:(UIManagedDocument *)lessonsDatabase{ if ( _lessonsDatabase != lessonsDatabase ) { _lessonsDatabase = lessonsDatabase; [self useDocument]; } } - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; self.title = NSLocalizedString(@"Lessons title",@"Lessons title"); if (!self.lessonsDatabase) { // We'll create a default database if none is set NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDirectory] lastObject]; url = [url URLByAppendingPathComponent:@"Default Espagram database"]; UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url]; NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; doc.persistentStoreOptions = options; self.lessonsDatabase = doc; } } - (void)viewDidUnload { [super viewDidUnload]; [self.lessonsDatabase closeWithCompletionHandler:^(BOOL success) { NSLog(@"Database closed"); }]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Lesson cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; Lesson *lesson = [self.fetchedResultsController objectAtIndexPath:indexPath]; NSLog(@"Showing lesson: %@", lesson.title); cell.textLabel.text = lesson.title; cell.detailTextLabel.text = lesson.subTitle; return cell; } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSIndexPath * indexPath = [self.tableView indexPathForCell:sender]; Lesson * lesson = [self.fetchedResultsController objectAtIndexPath:indexPath]; if ( [segue.identifier isEqualToString:@"Testing"]){ NSLog(@"Preparing for segue Testing"); if ([segue.destinationViewController respondsToSelector:@selector(setConjugator:)]) { [segue.destinationViewController setConjugator:self.conjugator]; } if ([segue.destinationViewController respondsToSelector:@selector(setLesson:)]) { [segue.destinationViewController setLesson:lesson]; [segue.destinationViewController setTitle:lesson.title]; } } if ( [segue.identifier isEqualToString:@"Add new Lesson"]){ NSLog(@"Preparing for segue Add new Lesson"); [segue.destinationViewController setDataSource:self]; } if ( [segue.identifier isEqualToString:@"Show Words In Lesson"]){ NSLog(@"Preparing for segue Show Words In Lesson"); if ([segue.destinationViewController respondsToSelector:@selector(setLesson:)]) { [segue.destinationViewController setLesson:lesson]; } } } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { Lesson * lesson = [self.fetchedResultsController objectAtIndexPath:indexPath]; if ( [lesson.verbs count] == 0) { // Lesson contains no words yet.. so go to the WordsInLessonView to add them // sender is the selected cell [self performSegueWithIdentifier:@"Show Words In Lesson" sender:[self.tableView cellForRowAtIndexPath:indexPath]]; } else { [self performSegueWithIdentifier:@"Testing" sender:[self.tableView cellForRowAtIndexPath:indexPath]]; } } - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"Show Words In Lesson" sender:[self.tableView cellForRowAtIndexPath:indexPath]]; } // 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 //[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; Lesson * selectedLesson = [self.fetchedResultsController objectAtIndexPath:indexPath]; [[self.lessonsDatabase managedObjectContext] deleteObject:selectedLesson]; } // 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 // } } @end