NewBeiDouContactModel.swift 1.93 KB
//
//  NewBeiDouContactModel.swift
//  HDFwear
//
//  Created by admin on 2023/11/17.
//

import UIKit
import HandyJSON
import SwiftDate

enum NewBeiDouContactType: Int, HandyJSONEnum {
    case emergency = 1
    case general = 2
}

class NewBeiDouContactModel: NSObject {
    required override init() { }
    
    var name: String = ""
    var phone: String = ""
    var type: NewBeiDouContactType = .general
    
    override var description: String {
         return "Name: \(name), Phone: \(phone), Type: \(type.rawValue)"
     }

    init(name: String, phone: String, type: NewBeiDouContactType) {
        self.name = name
        self.phone = phone
        self.type = type
    }
    
    class func getNewBeiDouContact(from data: [UInt8]) -> [NewBeiDouContactModel]? {
        var index = 0
        var contacts: [NewBeiDouContactModel] = []

        guard data.count >= 1 else { return nil }

        let contactsCount = Int(data[index])
        index += 1

        for _ in 0..<contactsCount {
            guard index + 2 < data.count else { return nil }

            let nameLength = Int(data[index])
            index += 1

            let nameData = Array(data[index..<(index + nameLength)])
            guard let name = String(bytes: nameData, encoding: .utf8) else { return nil }
            index += nameLength

            let phoneLength = Int(data[index])
            index += 1

            let phoneData = Array(data[index..<(index + phoneLength)])
            guard let phone = String(bytes: phoneData, encoding: .ascii) else { return nil }
            index += phoneLength

            let typeRawValue = data[index]
            index += 1

            if let type = NewBeiDouContactType(rawValue: Int(typeRawValue)) {
                let contact = NewBeiDouContactModel(name: name, phone: phone, type: type)
                contacts.append(contact)
            } else {
                return nil
            }
        }

        return contacts
    }


}