//
//  Service.swift
//  MVM5G
//
//  Created by Matt Bruce on 4/13/22.
//  Copyright © 2022 Kyle. All rights reserved.
//

import Foundation
import CoreBluetooth

public struct ServiceModel: CBUUIDIdentifiable, Codable, Equatable {
    var uuid: CBUUID
    var characteristics: [CharacteristicModel]
    
    enum CodingKeys: String, CodingKey {
        case uuid
        case characteristicUUID
    }

    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        let _uuid = try typeContainer.decode(String.self, forKey: .uuid)
        uuid = CBUUID(string: _uuid)
        let _characteristics = try typeContainer.decode([String: String].self, forKey: .characteristicUUID)
        characteristics = _characteristics.map { key, value in
            return CharacteristicModel(uuid: CBUUID(string: value), name: CharacteristicType(rawValue: key) ?? .unknown)
        }
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(uuid.uuidString, forKey: .uuid)
        var _characteristics: [String: String] = [:]
        characteristics.forEach { c in
            _characteristics[c.name.rawValue] = c.uuid.uuidString
        }
        try container.encode(_characteristics, forKey: .characteristicUUID)
    }
    
    public static func == (lhs: ServiceModel, rhs: ServiceModel) -> Bool {
        return lhs.uuid == rhs.uuid && lhs.characteristics == rhs.characteristics
    }
}
