//
//  KMAdvertisementImage.swift
//  KMAdvertisement
//
//  Created by lizhe on 2023/1/12.
// 图片缓存

import Foundation
import AppKit

typealias KMAdvertisementImageCompletion = (_ image: NSImage) -> Void
class KMAdvertisementImage: NSObject {
    static func imageWithURL(url : URL?, completion: KMAdvertisementImageCompletion?) -> NSImage {
        var image: NSImage = NSImage()
        if url != nil {
            //获取缓存图片是否存在
            let imageString: String = KMAdvertisementImageCache.fetchImageCache(url: url!)
            if imageString != "" {
                //存在获取本地图片
                image = NSImage.init(contentsOfFile: imageString) ?? NSImage()
                if completion != nil {
                    completion!(image)
                }
            } else {
                let path = KMAdvertisementImageCache.kImageCacheFilePath
                let filePath = (path as String) + "/" + (NSString(string: NSString(string: url!.path).lastPathComponent) as String)
                KMAdvertisementRequestServer.requestServer.downLoad(inputURL: url!, filePath: filePath) { progress in
                    
                } completion: { task, responseObject, error in
                    if completion != nil {
                        DispatchQueue.main.async {
                            image = NSImage.init(contentsOfFile: KMAdvertisementImageCache.fetchImageCache(url: url!)) ?? NSImage()
                            completion!(image)
                        }
                    }
                }
            }
        }
        return image
    }
}



class KMAdvertisementImageCache: NSObject {
    static let kImageCacheFilePath: NSString = NSTemporaryDirectory() + "Advertisement/ImageCache" as NSString
    
    static func saveImageCache(image: NSImage, name: String) {
        if image.size.width != 0 {
            
            let path = KMAdvertisementImageCache.kImageCacheFilePath
            let filePath = (path as String) + "/" + NSString(string: name).deletingPathExtension + ".png"
            if (!FileManager.default.fileExists(atPath: path as String)) {
                try?FileManager.default.createDirectory(atPath: path as String, withIntermediateDirectories: true, attributes: nil)
            }
            
            #if os(iOS)
            
//            [UIImagePNGRepresentation(image) writeToFile:path + name
//                                              atomically:YES]
            #elseif os(OSX)
            let cgimage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)
            if cgimage != nil {
                let rep = NSBitmapImageRep.init(cgImage: cgimage!)
                try?rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: filePath))
            } else {
                try?image.tiffRepresentation?.write(to: URL(fileURLWithPath: filePath))
            }
            print(path)
            #endif
        }
    }
    
    static func fetchImageCache(url: URL) -> String {
        if (!FileManager.default.fileExists(atPath: kImageCacheFilePath as String)) {
            try?FileManager.default.createDirectory(atPath: kImageCacheFilePath as String, withIntermediateDirectories: true, attributes: nil)
        }
        
        var string = ""
        let name = NSString(string: url.path).lastPathComponent
        let manager = FileManager.default
        let contentsOfPath = try? manager.contentsOfDirectory(atPath: kImageCacheFilePath as String)
        
        if (contentsOfPath!.contains(name)) {
            string = (kImageCacheFilePath as String) + "/" + name
//            print("图片存在" + string)
        } else {
//            print("图片不存在" + (kImageCacheFilePath as String) + "/" + name)
        }
        return string
    }
}
