<commit_before>//
//  PersistenceController.swift
//  NewCoreDataStack
//
//  Created by BJ on 6/4/15.
//  Copyright (c) 2015 Six Five Software, LLC. All rights reserved.
//

import Foundation
import CoreData


public enum CoreDataStoreType {
    case SQLite, InMemory, Binary
    
    public var storeTypeString: String {
        switch self {
        case .SQLite:
            return NSSQLiteStoreType
        case .InMemory:
            return NSInMemoryStoreType
        case .Binary:
            return NSBinaryStoreType
        }
    }
}


public struct PersistenceController {

    public let mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    private let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
    
    private let callback: (Void -> Void)?
    
    public init(modelName: String, storeType: CoreDataStoreType = .SQLite, callback: (Void -> Void)? = nil) {
        self.callback = callback
        
        let modelURL = NSBundle.mainBundle().URLForResource(modelName, withExtension: "momd")!
        let mom = NSManagedObjectModel(contentsOfURL: modelURL)!
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: mom)
        
        privateContext.persistentStoreCoordinator = coordinator
        mainContext.parentContext = privateContext
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
            let psc = self.privateContext.persistentStoreCoordinator!
            let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true, NSSQLitePragmasOption : ["journal_mode" : "DELETE"]] as [NSObject : AnyObject]
            
            let fileManager = NSFileManager.defaultManager()
            let documentsURL = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
            let storeURL = documentsURL.URLByAppendingPathComponent("\(modelName).sqlite")
    
            try! psc.addPersistentStoreWithType(storeType.storeTypeString, configuration: nil, URL: storeURL, options: options)
            
            dispatch_async(dispatch_get_main_queue()) {
                callback?()
            }
        }
    }
    
    public func save() {
        
        if !privateContext.hasChanges && !mainContext.hasChanges {
            return
        }
        
        mainContext.performBlockAndWait {
//            var error: NSError?
//            let mainSave = self.mainContext.save(&error)
            try! self.mainContext.save()
            
//            if !mainSave {
//                print("error saving main context. code: \(error?.code ?? 0). error: \(error?.localizedDescription ?? String())")
//            }
            
            self.privateContext.performBlock {
//                var privateError: NSError?
//                let privateSave = self.privateContext.save(&privateError)
                try! self.privateContext.save()
                
//                if !privateSave {
//                    print("error saving private context. code: \(error?.code ?? 0). error: \(error?.localizedDescription ?? String())")
//                }
            }
        }<commit_msg>Fix and clean up Persistence save function.<commit_after>//
//  PersistenceController.swift
//  NewCoreDataStack
//
//  Created by BJ on 6/4/15.
//  Copyright (c) 2015 Six Five Software, LLC. All rights reserved.
//

import Foundation
import CoreData


public enum CoreDataStoreType {
    case SQLite, InMemory, Binary
    
    public var storeTypeString: String {
        switch self {
        case .SQLite:
            return NSSQLiteStoreType
        case .InMemory:
            return NSInMemoryStoreType
        case .Binary:
            return NSBinaryStoreType
        }
    }
}

public struct PersistenceController {

    public let mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    private let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
    
    private let callback: (Void -> Void)?
    
    public init(modelName: String, storeType: CoreDataStoreType = .SQLite, callback: (Void -> Void)? = nil) {
        self.callback = callback
        
        let modelURL = NSBundle.mainBundle().URLForResource(modelName, withExtension: "momd")!
        let mom = NSManagedObjectModel(contentsOfURL: modelURL)!
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: mom)
        
        privateContext.persistentStoreCoordinator = coordinator
        mainContext.parentContext = privateContext
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
            let psc = self.privateContext.persistentStoreCoordinator!
            let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true, NSSQLitePragmasOption : ["journal_mode" : "DELETE"]] as [NSObject : AnyObject]
            
            let fileManager = NSFileManager.defaultManager()
            let documentsURL = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
            let storeURL = documentsURL.URLByAppendingPathComponent("\(modelName).sqlite")
    
            try! psc.addPersistentStoreWithType(storeType.storeTypeString, configuration: nil, URL: storeURL, options: options)
            
            dispatch_async(dispatch_get_main_queue()) {
                callback?()
            }
        }
    }
    
    public func save() {
        
        if !privateContext.hasChanges && !mainContext.hasChanges {
            return
        }
        
        mainContext.performBlockAndWait {
            if let _ = try? self.mainContext.save() {
                self.privateContext.performBlock {
                    if let _ =  try? self.privateContext.save() {
                        // success
                    }
                }
            }
        }
{'fraction_non_alphanumeric': 0.08278688524590164, 'fraction_numerical': 0.003278688524590164, 'mean_word_length': 2.317563893420337, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3942204', 'n_tokens_mistral': 1614, 'n_tokens_neox': 1559, 'n_words': 337}