espagram/Espagram/EspagramLessonViewController.m
Abel Fokkinga 3013ee52c4 Version 1.1
- Added localised descriptions for all the tenses.
- After selecting a lesson, you will get a screen where you can see both the words in the lesson or start a multiple choice test.
- Lay-out fixes
- UI improvements
2013-01-02 17:33:00 -02:00

348 lines
13 KiB
Objective-C

//
// 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 "Verb+Create.h"
#import "EspagramTestViewController.h"
@interface EspagramLessonViewController ()
@property UITabBarController * tabBarController;
@end
@implementation EspagramLessonViewController
@synthesize lessonsDatabase = _lessonsDatabase;
@synthesize lesson = _lesson;
@synthesize conjugator = _conjugator;
@synthesize tense = _tense;
@synthesize tabBarController;
- (IBAction)AddButtonPressed:(id)sender {
NSLog(@"Selected lesson %@", self.lesson.title);
[self performSegueWithIdentifier:@"Add A Word To Lesson" sender:self];
}
- (void) addWord:(NSString *)word withMeaning:(NSString *)meaning{
if ( word ) {
NSLog(@"Selected lesson %@", self.lesson.title);
[Verb addVerb:word andMeaning:meaning toLesson:self.lesson];
}
[[self parentViewController] dismissViewControllerAnimated:TRUE completion:^{
NSLog(@"Word added");
}];
if ( self.lesson.verbs.count > 0 && self.tabBarController ) {
// Words in lesson, enable tabs
NSArray *tabItems = self.tabBarController.tabBar.items;
for (UIBarItem *tabItem in tabItems)
{
[tabItem setEnabled:true];
}
}
}
- (void) cancelAddingWord{
[[self parentViewController] dismissViewControllerAnimated:TRUE completion:^{ NSLog(@"Adding a word cancelled");
}];
}
- (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]]) {
NSLog(@"No database exists");
[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)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController {
}
- (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
NSFileManager * fileManager = [NSFileManager defaultManager];
NSURL *storeURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDirectory] lastObject] URLByAppendingPathComponent: @"Default Espagram database"];
NSLog(@"DB url: %@", storeURL.path);
if (![fileManager fileExistsAtPath:storeURL.path]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Default Espagram database" ofType:@"sqlite"];
//NSString *defaultStorePath = [[[NSBundle mainBundle] resourcePath]
// stringByAppendingPathComponent:@"Default Espagram database"];
if ( [fileManager fileExistsAtPath:defaultStorePath]) {
NSLog(@"Default DB present in app");
NSError *error;
[fileManager copyItemAtPath:defaultStorePath toPath:storeURL.path error:&error];
NSLog(@"%@",error.debugDescription );
}
}
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;
NSString * lessonDescription = lesson.subTitle;
if (lessonDescription.length == 0 && [lesson.verbs count] > 0 ) {
for ( Verb * v in lesson.verbs) {
if (lessonDescription.length == 0) {
lessonDescription = v.verb;
} else {
lessonDescription = [[lessonDescription stringByAppendingString:@", "] stringByAppendingString:v.verb];
if ( lessonDescription.length > 50)
break;
}
}
}
cell.detailTextLabel.text = lessonDescription;
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ( [segue.identifier isEqualToString:@"Testing"]){
NSLog(@"Preparing for segue Testing");
NSIndexPath * indexPath = [self.tableView indexPathForCell:sender];
self.lesson = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([segue.destinationViewController respondsToSelector:@selector(setConjugator:)]) {
[segue.destinationViewController setConjugator:self.conjugator];
}
if ([segue.destinationViewController respondsToSelector:@selector(setLesson:)]) {
[segue.destinationViewController setLesson:self.lesson];
[segue.destinationViewController setTitle:self.lesson.title];
}
}
if ( [segue.identifier isEqualToString:@"Testing Tab Bar"]){
NSLog(@"Preparing for segue Testing Tab Bar");
NSIndexPath * indexPath = [self.tableView indexPathForCell:sender];
self.lesson = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([segue.destinationViewController respondsToSelector:@selector(setDelegate:)]) {
[segue.destinationViewController setDelegate:self];
[segue.destinationViewController setTitle:self.lesson.title];
UIBarButtonItem * rightButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(AddButtonPressed:)];
UIViewController *rootViewController = segue.destinationViewController;
rootViewController.navigationItem.rightBarButtonItem = rightButton;
}
self.tabBarController = segue.destinationViewController;
if ( self.lesson.verbs.count == 0 ) {
// No words in lesson.. disable tabs
NSArray *tabItems = self.tabBarController.tabBar.items;
for (UIBarItem *tabItem in tabItems)
{
[tabItem setEnabled:false];
}
}
NSLog(@"Count viewControllers: %d", [self.tabBarController viewControllers].count);
for ( id vc in [self.tabBarController viewControllers] ) {
if ( [vc respondsToSelector:@selector(setLesson:)]) {
[vc setLesson:self.lesson];
}
}
}
if ( [segue.identifier isEqualToString:@"Show Words In Lesson"]){
NSIndexPath * indexPath = [self.tableView indexPathForCell:sender];
self.lesson = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"Preparing for segue Show Words In Lesson");
if ([segue.destinationViewController respondsToSelector:@selector(setLesson:)]) {
[segue.destinationViewController setLesson:self.lesson];
}
}
if ( [segue.identifier isEqualToString:@"Add new Lesson"]){
NSLog(@"Preparing for segue Add new Lesson");
[segue.destinationViewController setDataSource:self];
}
if ( [segue.identifier isEqualToString:@"Add A Word To Lesson"]) {
[segue.destinationViewController setDataSource:self];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:@"Testing Tab Bar" sender:[self.tableView cellForRowAtIndexPath:indexPath]];
// [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