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

import Foundation
import CoreFoundation
import CoreServices
import QuickLook
import CoreData


@_cdecl("GeneratePreviewForURL")
func GeneratePreviewForURL(thisInterface:UnsafeRawPointer,
                                            preview: QLPreviewRequest,
                                            url: CFURL,
                                            contentTypeUTI: CFString,
                                            options: CFDictionary) -> OSStatus
{
    autoreleasepool
    {
        let theManagedObjectContext: NSManagedObjectContext?
            = coreDataManagedObjectContext(bundle: QLPreviewRequestGetGeneratorBundle(preview).takeRetainedValue(),
                                           url: url,
                                           contentTypeUTI: contentTypeUTI)
        
        if theManagedObjectContext == nil { return } // CoreDataのエラー：autoreleasepoolのスコープを抜ける
        
        if QLPreviewRequestIsCancelled(preview) { return }// キャンセル処理：autoreleasepoolのスコープを抜ける
        
        let theAllToDoItems = try! theManagedObjectContext!.fetch(ToDoItem.sortedToDoItemsFetchRequest())

        if QLPreviewRequestIsCancelled(preview) { return } // キャンセル処理：autoreleasepoolのスコープを抜ける

        // 表示するデータを構築する
        let theData: CFData = representationDataFrom(ToDoItems: theAllToDoItems)
        
        if QLPreviewRequestIsCancelled(preview) { return } // キャンセル処理：autoreleasepoolのスコープを抜ける

        let theProperties: CFDictionary = [
            kQLPreviewPropertyTextEncodingNameKey: "UTF-8",
            kQLPreviewPropertyAttachmentsKey: [:],
            kQLPreviewPropertyMIMETypeKey: "text"
            //                                              kQLPreviewPropertyMIMETypeKey: "text/html"
            ] as CFDictionary

        QLPreviewRequestSetDataRepresentation(preview,
                                              theData,
                                              kUTTypePlainText,
//                                                    kUTTypeHTML,
                                              theProperties)
            
        print("Preview in Swift")
    }
    

    return noErr
}

@_cdecl("CancelPreviewGeneration")
func CancelPreviewGeneration(thisInterface:UnsafeRawPointer,
                             preview: QLPreviewRequest) -> Void
{
    // Implement only if supported
}
