//
//  AppDelegate.m
//  KaiLiTe
//
//  Created by boosal on 2016/9/1.
//  Copyright © 2016年 boosal. All rights reserved.
//

#import "KLTAppDelegate.h"
//#import <Masonry/Masonry.h>
#import <AVFoundation/AVFoundation.h>
#import "KLTUserDefautKeyDefine.h"
#import "KLTDatabaseHandler.h"
#import "KLTLaunchConfiguration.h"
#import "UIColor+KLTUI.h"

@implementation KLTAppDelegate

+ (KLTRunLog * )getCurrentKLTRunLog {
    static dispatch_once_t pred;
    static KLTRunLog *currentRunLog;
    dispatch_once(&pred, ^{
        currentRunLog = [[KLTRunLog alloc] init];
    });
    return currentRunLog;
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.boosal.KaiLiTe" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyTatva" withExtension:@"momd"];
    if (modelURL == nil) {
        NSLog(@"Error: Could not find model URL for MyTatva.momd");
        abort(); // or handle gracefully
    }
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"KaiLiTe.sqlite"];
    NSError *error = nil;
    NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
                                       NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES],
                                       NSInferMappingModelAutomaticallyOption, nil];

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:optionsDictionary error:&error]) {
        
        //NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}





- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

- (void)deleteAllCoreData {
    NSPersistentStoreCoordinator *storeCoordinator = self.persistentStoreCoordinator;
    NSManagedObjectContext *context = self.managedObjectContext;
    NSManagedObjectModel *model = storeCoordinator.managedObjectModel;

    for (NSEntityDescription *entity in model.entities) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:entity.name];

        NSBatchDeleteRequest *deleteRequest = [[NSBatchDeleteRequest alloc] initWithFetchRequest:fetchRequest];

        NSError *deleteError = nil;
        [storeCoordinator executeRequest:deleteRequest withContext:context error:&deleteError];

        if (deleteError) {
            NSLog(@"Failed to delete entity %@: %@", entity.name, deleteError.localizedDescription);
        } else {
            NSLog(@"Successfully deleted entity %@", entity.name);
        }
    }

    [self saveContext];
}


@end
