import Foundation

struct SRVRecord: Codable & Equatable {
    let priority: Int
    let weight: Int
    let port: Int
    let target: String
    let isSecure: Bool

    init?(data: Data) {
        guard data.count > 6 else {
            return nil
        }
        priority = Int(data[0]) * 256 + Int(data[1])
        weight = Int(data[2]) * 256 + Int(data[3])
        port = Int(data[4]) * 256 + Int(data[5])

        var workingTarget = ""
        for byte in data[7...(data.count - 1)] {
            var symbol = byte
            symbol = symbol < 33 ? 46 : symbol
            if let char = String(data: Data([symbol]), encoding: .utf8) {
                workingTarget += char
            }
        }
        target = workingTarget
        isSecure = target.starts(with: "_xmpps")
    }

    init(fallbackTarget: String) {
        target = fallbackTarget
        port = 5222
        priority = 0
        weight = 0
        isSecure = false
    }

    var description: String {
        "target: \(target) port: \(port) priority: \(priority) weight: \(weight)"
    }
}
