//
//  KMLightMemberCache.swift
//  KMLightMember
//
//  Created by lizhe on 2022/11/25.
//

enum KMLightMemberCacheType: String {
    case info = "lightMemberInfoCache.plist"
    case token = "lightMemberTokenCache.plist"
}

class KMLightMemberCache: NSObject {
    let kFilePath: NSString = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path + "KMLightMemberCache" as NSString
    
    //单例
    public static let cache = KMLightMemberCache()
    //存储
    func saveData(data: NSDictionary, type: KMLightMemberCacheType = .info) {
        let string: NSString = (kFilePath as String) + "/" + type.rawValue as NSString

        if (!FileManager.default.fileExists(atPath: string.deletingLastPathComponent as String)) {
            try?FileManager.default.createDirectory(atPath: string.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
        }
        
        if (!FileManager.default.fileExists(atPath: string as String)) {
            FileManager.default.createFile(atPath: string as String, contents: nil)
        }
        
        //获取有用的参数
//        let dic: NSMutableDictionary = [:]
//        for key in data.allKeys {
//            let object = data.object(forKey: key)
//            if let subDictionary = object as? [NSDictionary] {
//
//            } else if (!(object is NSNull)) {
//                dic.setObject(object as Any, forKey: key as! NSCopying)
//            }
//        }
        
//        let dic: [String: Any] = data.allKeys // 待处理的字典数据
        let result = removeNullValuesFromDictionary(data as! [String : Any])
        
//        dic.removeObject(forKey: "subscriptionInfoList")
        
        let saveData: NSArray = [result]
        let success = saveData.write(toFile: string.expandingTildeInPath as String, atomically: true)

        if (success == true) {
            KMPrint("成功 -" + (string.expandingTildeInPath as String))
        } else {
            KMPrint("失败 -" + (string.expandingTildeInPath as String))
        }
    }

   //读取
    func readData( type: KMLightMemberCacheType = .info) -> NSDictionary {
        let string: NSString = (kFilePath as String) + "/" + type.rawValue as NSString
        
        let data =  NSArray.init(contentsOfFile: string.expandingTildeInPath as String)
        if (data != nil) {
            return data!.firstObject as! NSDictionary
        } else {
            return [:]
        }
    }
    
    func clean() {
        if (FileManager.default.fileExists(atPath: kFilePath as String)) {
            try?FileManager.default.removeItem(atPath: kFilePath as String)
        }
    }
}

extension KMLightMemberCache {
    /**
     */
    func removeNullValuesFromDictionary(_ dictionary: [String: Any]) -> [String: Any] {
        var result: [String: Any] = [:]

        for (key, value) in dictionary {
            if let subDictionary = value as? [NSDictionary] {
                // 子集为数组,则递归遍历子字典并进行处理
                var array: [Any] = []
                for item in subDictionary {
                    let cleanedSubDictionary = removeNullValuesFromDictionary(item as! [String : Any])
                    array.append(cleanedSubDictionary)
                }
                if !array.isEmpty {
                    result[key] = array
                }
            } else if let subDictionary = value as? [String: Any] {
                // 子集为字典,则递归遍历子字典并进行处理
                let cleanedSubDictionary = removeNullValuesFromDictionary(subDictionary)
                if !cleanedSubDictionary.isEmpty {
                    result[key] = cleanedSubDictionary
                }
            } else if !(value is NSNull) {
                // 子集不为 null,则将键值对添加到结果字典中
                result[key] = value
            }
//            else if (value is NSNull) {
//                result[key] = ""
//            }
        }

        return result
    }
}