import Foundation

/// Thin plist helpers shared by the profile builder and the check-in/command protocol. All MDM wire
/// bodies are XML property lists; `PropertyListSerialization` (present on Darwin and swift-corelibs
/// Foundation) does the encoding so the module stays cross-platform and dependency-free here.
public enum MDMPlist {
    public enum PlistError: Error, CustomStringConvertible {
        case notADictionary
        case serialization(String)

        public var description: String {
            switch self {
            case .notADictionary: return "expected a top-level plist dictionary"
            case .serialization(let s): return "plist serialization failed: \(s)"
            }
        }
    }

    /// Serialize a dictionary to XML-plist data.
    public static func serialize(_ object: [String: Any]) throws -> Data {
        do {
            return try PropertyListSerialization.data(
                fromPropertyList: object, format: .xml, options: 0)
        } catch { throw PlistError.serialization("\(error)") }
    }

    /// Parse plist data (XML or binary) into a dictionary, or throw.
    public static func parse(_ data: Data) throws -> [String: Any] {
        let obj = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
        guard let dict = obj as? [String: Any] else { throw PlistError.notADictionary }
        return dict
    }
}
