//
//  GenerateThumbnailForURL.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("GenerateThumbnailForURL")
func GenerateThumbnailForURL(thisInterface:UnsafeRawPointer,
                                            thumbnail: QLThumbnailRequest,
                                            url: CFURL,
                                            contentTypeUTI: CFString,
                                            options: CFDictionary,
                                            maxSize: CGSize) -> OSStatus
{
    autoreleasepool
    {
        let theManagedObjectContext: NSManagedObjectContext?
            = coreDataManagedObjectContext(bundle: QLThumbnailRequestGetGeneratorBundle(thumbnail).takeRetainedValue(),
                                           url: url,
                                           contentTypeUTI: contentTypeUTI)

        if theManagedObjectContext == nil { return } // CoreDataのエラー：autoreleasepoolのスコープを抜ける

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

        let theAllToDoItems = try! theManagedObjectContext!.fetch(ToDoItem.sortedToDoItemsFetchRequest())

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

        // 表示するデータを構築する
        let theData: CFData = representationDataFrom(ToDoItems: theAllToDoItems)

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

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

        QLThumbnailRequestSetThumbnailWithDataRepresentation(thumbnail,
                                                             theData,
                                                             kUTTypePlainText,
                                                             [:] as CFDictionary,
                                                             theProperties)

        print("Thumbnail in Swift");
    }
    
    return noErr
}

@_cdecl("CancelThumbnailGeneration")
func CancelThumbnailGeneration(thisInterface:UnsafeRawPointer,
                               thumbnail: QLThumbnailRequest) -> Void
{
    // Implement only if supported
}

