//
//  ToDoListQuickLookUtility.swift
//  ToDoListQuickLook
//
//  Created by narita on 2018/04/28.
//  Copyright © 2018年 narita. All rights reserved.
//

import Foundation
import CoreFoundation
import CoreServices
import CoreData

// PreviewとThumbnailの共通部分。CoreDataの準備
func coreDataManagedObjectContext(bundle: CFBundle, url: CFURL, contentTypeUTI: CFString)-> NSManagedObjectContext?
{
    do
    {
        let theURL = CFBundleCopyResourceURL(bundle,
                                             "Document" as CFString,
                                             "momd" as CFString,
                                             "" as CFString) as URL?
        
        if theURL == nil { return nil }
        
        let theManagedObjectModel: NSManagedObjectModel? = NSManagedObjectModel(contentsOf: theURL!)
        
        if theManagedObjectModel == nil { return nil }

        let thePersistentStoreCoordinator: NSPersistentStoreCoordinator =
            NSPersistentStoreCoordinator(managedObjectModel: theManagedObjectModel!)

        let theContentTypeUTI: String = contentTypeUTI as String
        let theStoreType: String
        
        switch theContentTypeUTI
        {
            case "com.mindto01s.ToDoList.binary":
                theStoreType = NSBinaryStoreType
            
            case "com.mindto01s.ToDoList.sqlite":
                theStoreType = NSSQLiteStoreType
            
            case "com.mindto01s.ToDoList.xml":
                theStoreType = NSXMLStoreType
            default:
                theStoreType = "" // エラー
                return nil
        }
        
        try thePersistentStoreCoordinator.addPersistentStore(ofType: theStoreType,
                                                             configurationName: nil,
                                                             at: url as URL,
                                                             options: nil)
        
        let theManagedObjectContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        theManagedObjectContext.persistentStoreCoordinator = thePersistentStoreCoordinator
        
        return theManagedObjectContext
    }
    catch
    {
        // 致命的なエラーで終了
    }

    return nil
}

// CoreDataからFetchした配列からテキスト(コメントを書き換えてhtmlの時もあるかも)データを作る。
func representationDataFrom(ToDoItems: Array<ToDoItem>)  -> CFData
{
    var theResultString: String = ""
    //            var theResultString: String = "<HTML><body>xxxxxxx</body></HTML>"
    
    for i in ToDoItems
    {
        theResultString += i.doneAndMemoString + "\n"
    }
    
    return theResultString.data(using: .utf8)! as CFData
}

