//
//  NSObject+Decodable.swift
//  YYKit
//
//  Created by OneeChan on 2025/10/13.
//

import Foundation

// MARK: 为了从 YYModel 过度到 Decodable，增加解析的兼容代码
extension Decodable {
    static func decode(param: [AnyHashable: Any]) -> Self? {
        guard let jsonData = getJsonData(param) else { return nil }
        guard let model = try? JSONDecoder().decode(Self.self, from: jsonData) else { return nil }
        
        return model
    }
    
    private static func getJsonData(_ param: [AnyHashable: Any]) -> Data? {
        if !JSONSerialization.isValidJSONObject(param) {
            return nil
        }
        guard let data = try? JSONSerialization.data(withJSONObject: param, options: []) else {
            return nil
        }
        return data
    }
}

extension NSObject {
    @objc static func tryDecode(from param: [AnyHashable: Any]) -> Self? {
        guard let decodableType = self as? Decodable.Type else {
            return nil
        }
        return decodableType.decode(param: param) as? Self
    }
}
