import Foundation
import UIKit
import BaiduMapAPI_Map

extension MapViewImpl {
    func loadImage(_ iconPath: String) -> UIImage? {
        if iconPath.isEmpty {
            return nil
        }
        
        // 绝对路径直接加载
        if iconPath.hasPrefix("/") {
            if let image = UIImage(contentsOfFile: iconPath) {
                return image
            }
        }
        
        let normalizedPath = self.normalizeIconPath(iconPath)
        
        if let image = self.loadImageFromStaticDirectory(normalizedPath) {
            return image
        }
        
        if let image = self.loadImageFromPluginResources(normalizedPath) {
            return image
        }
        
        if let image = self.loadImageFromBundleRoot(normalizedPath) {
            return image
        }
        
        if let image = self.loadImageByImageNamed(normalizedPath) {
            return image
        }
        
        NSLog("loadImage failed: \(iconPath)")
        return nil
    }
    
    private func normalizeIconPath(_ rawPath: String) -> String {
        if rawPath.hasPrefix("/") {
            return String(rawPath.dropFirst())
        }
        return rawPath
    }
    
    private func loadImageFromStaticDirectory(_ normalizedPath: String) -> UIImage? {
        if !normalizedPath.hasPrefix("static/") {
            return nil
        }
        
        let relativePath = String(normalizedPath.dropFirst("static/".count))
        return self.loadImageFromDirectory(relativePath, directoryPrefix: "static")
    }
    
    private func loadImageFromPluginResources(_ normalizedPath: String) -> UIImage? {
        if normalizedPath.hasPrefix("Resources/") {
            let relativePath = String(normalizedPath.dropFirst("Resources/".count))
            if let image = self.loadImageFromDirectory(relativePath, directoryPrefix: "Resources") {
                return image
            }
        }
        
        if let image = self.loadImageFromDirectory(normalizedPath, directoryPrefix: "Resources") {
            return image
        }
        
        return nil
    }
    
    private func loadImageFromBundleRoot(_ normalizedPath: String) -> UIImage? {
        let nsPath = normalizedPath as NSString
        let fileName = nsPath.deletingPathExtension
        let fileExt = nsPath.pathExtension
        
        if fileName.isEmpty {
            return nil
        }
        
        if let filePath = Bundle.main.path(forResource: fileName, ofType: fileExt.isEmpty ? nil : fileExt) {
            NSLog("loadImageFromBundleRoot hit path = \(filePath)")
            if let image = UIImage(contentsOfFile: filePath) {
                return image
            }
        }
        
        return nil
    }
    
    private func loadImageByImageNamed(_ normalizedPath: String) -> UIImage? {
        if let image = UIImage(named: normalizedPath) {
            return image
        }
        
        let lastPath = (normalizedPath as NSString).lastPathComponent
        if let image = UIImage(named: lastPath) {
            return image
        }
        
        let fileName = (lastPath as NSString).deletingPathExtension
        if !fileName.isEmpty {
            if let image = UIImage(named: fileName) {
                return image
            }
        }
        
        return nil
    }
    
    private func loadImageFromDirectory(_ relativePath: String, directoryPrefix: String) -> UIImage? {
        let nsPath = relativePath as NSString
        let fileName = nsPath.deletingPathExtension
        let fileExt = nsPath.pathExtension
        let subDir = nsPath.deletingLastPathComponent
        
        if fileName.isEmpty {
            return nil
        }
        
        let directory: String
        if subDir.isEmpty {
            directory = directoryPrefix
        }
        else {
            directory = directoryPrefix + "/" + subDir
        }
        
        if let filePath = Bundle.main.path(
            forResource: fileName,
            ofType: fileExt.isEmpty ? nil : fileExt,
            inDirectory: directory
        ) {
            NSLog("loadImageFromDirectory hit path = \(filePath)")
            if let image = UIImage(contentsOfFile: filePath) {
                return image
            }
        }
        
        return nil
    }
    
    public func colorFromString(_ value: String, _ fallback: UIColor) -> UIColor {
        if value.isEmpty {
            return fallback
        }
        
        if value.hasPrefix("#") {
            var alpha: CGFloat = 1.0
            var hex = String(value.dropFirst())
            // 兼容 CSS 3/4 位简写：#RGB -> #RRGGBB，#ARGB -> #AARRGGBB
            if hex.count == 3 {
                let chars = Array(hex)
                hex = "\(chars[0])\(chars[0])\(chars[1])\(chars[1])\(chars[2])\(chars[2])"
            } else if hex.count == 4 {
                let chars = Array(hex)
                hex = "\(chars[0])\(chars[0])\(chars[1])\(chars[1])\(chars[2])\(chars[2])\(chars[3])\(chars[3])"
            }
            if hex.count == 6 {
                let scanner = Scanner(string: hex)
                var hexValue: UInt64 = 0
                if scanner.scanHexInt64(&hexValue) {
                    let r = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
                    let g = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
                    let b = CGFloat(hexValue & 0x0000FF) / 255.0
                    return UIColor(red: r, green: g, blue: b, alpha: 1.0)
                }
            }
            else if hex.count == 8 {
                let alphaHex = String(hex.prefix(2))
                var alphaValue: UInt32 = 0
                Scanner(string: alphaHex).scanHexInt32(&alphaValue)
                alpha = CGFloat(alphaValue) / 255.0
                // 截取后面的颜色部分
                hex = String(hex.dropFirst(2))
                let scanner = Scanner(string: hex)
                var hexValue: UInt64 = 0
                if scanner.scanHexInt64(&hexValue) {
                    let r = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
                    let g = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
                    let b = CGFloat(hexValue & 0x0000FF) / 255.0
                    return UIColor(red: r, green: g, blue: b, alpha: alpha)
                }
            }
        }
        
        if value.hasPrefix("rgba(") && value.hasSuffix(")") {
            let content = value.replacingOccurrences(of: "rgba(", with: "").replacingOccurrences(of: ")", with: "")
            let parts = content.split(separator: ",")
            if parts.count == 4 {
                let r = CGFloat((Double(parts[0].trimmingCharacters(in: .whitespaces)) ?? 0) / 255.0)
                let g = CGFloat((Double(parts[1].trimmingCharacters(in: .whitespaces)) ?? 0) / 255.0)
                let b = CGFloat((Double(parts[2].trimmingCharacters(in: .whitespaces)) ?? 0) / 255.0)
                let a = CGFloat(Double(parts[3].trimmingCharacters(in: .whitespaces)) ?? 1.0)
                return UIColor(red: r, green: g, blue: b, alpha: a)
            }
        }
        
        return fallback
    }
}
