//
//  ProcessThumbnal.swift
//  ProcessCheckFile
//
//  Created by 朱东勇 on 2022/12/9.
//

import Foundation

import QuickLook
import QuickLookUI
import QuickLookThumbnailing

import ImageIO

let generator = QLThumbnailGenerator.shared

class ProcessThumbnal : NSObject {
    
    class func process(_ filePath:String, desPath:String) -> Bool {
        let kDefaultThumbnailSize = CGSizeMake(1000.0, 1000.0)
        
        return process(filePath, desPath: desPath, outputSize: kDefaultThumbnailSize)
    }
    
    class func process(_ filePath:String, desPath:String, outputSize:CGSize) -> Bool {
        if NSArray(array: ["JPG", "jpg"]).contains(NSString(string: filePath).pathExtension) {
            return true
        }
        
        if NSArray(array: ["bmp", "BMP", "PNG", "png", "JPG", "jpg"]).contains(NSString(string: filePath).pathExtension) {
            let imageSource = CGImageSourceCreateWithURL(URL.init(fileURLWithPath: filePath, isDirectory: false) as CFURL, nil)
            
            if nil == imageSource {
                return false
            }
            
            // Get the BMP image
            let cgimage = CGImageSourceCreateImageAtIndex(imageSource!, 0, nil)
            if nil == cgimage {
                return false
            }
            
            let rep = NSBitmapImageRep.init(cgImage: cgimage!)
            let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [:]);
            
            let url = URL.init(fileURLWithPath: desPath, isDirectory: false)
            try? data!.write(to: url)
            
            return true
        }
        
        var didFinished = false
        
        let semaphore = DispatchSemaphore(value: 0)
        let url = URL.init(fileURLWithPath: filePath, isDirectory: false)
        generator.generateRepresentations(for: QLThumbnailGenerator.Request.init(fileAt: url, size: outputSize, scale: 2.0, representationTypes: QLThumbnailGenerator.Request.RepresentationTypes.thumbnail),
                                          
                                          update: { (representation, type, error) in
            if nil != representation {
                let image = representation!.nsImage as NSImage
                
                if nil != image {
                    didFinished = true
                    
                    let rep = NSBitmapImageRep.init(cgImage: image.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
                    let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [:]);
                    
                    let url = URL.init(fileURLWithPath: desPath, isDirectory: false)
                    try? data!.write(to: url)
                }
            }
            
            semaphore.signal()
        })
        
        
        semaphore.wait()
        
        return didFinished
    }
    
}
