//
//  NSString+Extension.swift
//  PhoneManager
//
//  Created by edy on 2025/4/1.
//

import Foundation
import UIKit
import AVFoundation

extension UIColor {
    
    convenience init(_ hex:UInt32) {
        self.init(hex, 1.0)
    }
    
    convenience init(_ hex:UInt32 , _ alpha:Float = 1.0) {
        let red = Double((hex & 0xff0000) >> 16) / 255.0
        let green = Double((hex & 0xff00) >> 8) / 255.0
        let blue = Double((hex & 0xff) ) / 255.0
        self.init(red: red, green: green, blue: blue, alpha: 1)
    }
    
    func generateImage() -> UIImage? {
        let size = CGSize(width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        defer { UIGraphicsEndImageContext() }
        self.setFill()
        UIRectFill(CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

extension UIImage {
    
    class func Clear(_ color:UIColor = .clear) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        defer { UIGraphicsEndImageContext() }
        color.setFill()
        UIRectFill(rect)
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }
    
    func compressImage(_ scale: CGFloat , comp:@escaping ((_ image:UIImage)->Void)) -> Void {
        DispatchQueue.global().async {
            let imageData = self.jpegData(compressionQuality: scale)
            guard imageData != nil else {
                return
            }
            let img = UIImage(data: imageData!) ?? UIImage.Clear()
            DispatchQueue.main.async {
                comp(img)
            }
        }
    }

    func resizeAndCompressImage(_ scale: CGFloat = 0.5) -> UIImage {
        let size = self.size
        let widthRatio  = size.width * scale
        let heightRatio = size.height * scale
        let newSize = CGSize(width: widthRatio, height: heightRatio)
        let rect = CGRect(origin: .zero, size: newSize)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resizedImage ?? UIImage.Clear()
    }
    
}

extension String {

    // 获取文档路径
    func document() -> URL {
        let document = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        return document.appendingPathComponent(self)
    }
    
    func af() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
    }
  
    func delPhotoVideo(_ Nms:[String]) -> Void {
        for name in Nms {
            let path = self.af() + "/SecretIm/"
            let delFile = path + name
            SecretImageCache.share.removeImage(name)
            do {
                try FileManager.default.removeItem(atPath: delFile)
            }catch{
                Print("删除出错了")
            }
        }
    }
    
    func loadPhotoOrVideo( _ pv:@escaping ((Float64,UIImage)->Void) ) -> Void {
        if let img = SecretImageCache.share.loadCacheImage(self) {
            pv(img.1,img.0 ?? UIImage())
            return
        }
        let path = self.af() + "/SecretIm/"
        let abe = path + self
        if self.hasSuffix(".png") {
            guard let icon = UIImage(contentsOfFile: abe) else {
                pv(-1,UIImage.Clear())
                return
            }
            icon.compressImage(0.2) { image in
                SecretImageCache.share.saveImageCache(self, image)
                pv(-1,image)
            }
        }else{
            let url = "SecretIm".document().appendingPathComponent(self)
            let asset = AVAsset(url: url)
            let imageGenerator = AVAssetImageGenerator(asset: asset)
            imageGenerator.appliesPreferredTrackTransform = true
            let duration = asset.duration
            do {
                let cgImage = try imageGenerator.copyCGImage(at: CMTime(value: 0, timescale: 1), actualTime: nil)
                let icon = UIImage(cgImage: cgImage);
                icon.compressImage(0.2) { image in
                    SecretImageCache.share.saveImageCache(self, image,CMTimeGetSeconds(duration))
                    pv(CMTimeGetSeconds(duration) ,image)
                }
            } catch {
                pv(-1,UIImage() )
            }
        }
    }
    
    func removeEscapeCharacters() -> String {
        var cleaned = self
        cleaned = cleaned.replacingOccurrences(of: "\n", with: "")
                         .replacingOccurrences(of: "\t", with: "")
                         .replacingOccurrences(of: "\r", with: "")
        return cleaned
    }
    
    /// 动态计算宽度
    /// - Parameters:
    ///   - textWidth: <#textWidth description#>
    ///   - font: <#font description#>
    ///   - isBold: <#isBold description#>
    /// - Returns: <#description#>
    public func textWidthFromTextString(textHeight: CGFloat, font: UIFont) -> CGFloat {
        let dict: NSDictionary = NSDictionary(object: font,forKey: NSAttributedString.Key.font as NSCopying)
        let rect: CGRect = (self as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: textHeight), options: [NSStringDrawingOptions.truncatesLastVisibleLine, NSStringDrawingOptions.usesFontLeading,NSStringDrawingOptions.usesLineFragmentOrigin],attributes: dict as? [NSAttributedString.Key : Any] ,context: nil)
        return rect.size.width
    }
    

}

extension URL {
    
    // 获取 路径下所有文件
    func directorChildFile() -> [String] {
        let fileManager = FileManager.default
        _ = fileManager.fileExists(atPath: self.pathExtension )
        do {
            let fileNames = try fileManager.contentsOfDirectory(atPath: self.absoluteString)
            var filesOnly: [String] = []
            for fileName in fileNames {
                let fullPath = (self.absoluteString as NSString).appendingPathComponent(fileName)
                var isDirectory: ObjCBool = false
                if fileManager.fileExists(atPath: fullPath, isDirectory: &isDirectory), !isDirectory.boolValue {
                    filesOnly.append(fileName)
                }
            }
            return filesOnly
        } catch {
            print("获取文件列表失败: \(error.localizedDescription)")
            return []
        }
    }
    
    // 是否是文件夹
    func isDirect(_ create:Bool = true) -> Bool {
        var isDirectory: ObjCBool = false
        let exists = FileManager.default.fileExists(atPath: self.absoluteString, isDirectory: &isDirectory)
        if exists && isDirectory.boolValue {
            
        }else{
            if create {
                do {
                    try FileManager.default.createDirectory(at: self, withIntermediateDirectories: false, attributes: nil)
                }catch{
                }
            }
        }
        return exists && isDirectory.boolValue
    }
    
}


extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0..<Swift.min($0 + size, count)])
        }
    }
}
