//
//  Helper.swift
//  ABC Bluetooth Demo
//
//  Created by AB Circle on 2/9/2020.
//  Copyright © 2020-2024 AB Circle. All rights reserved.
//

import Foundation

/// Static Helper class. Contains generic helper functions
class Helper {

    /// Private initialiser
    private init() {
    }

    /// Converts entered data, e.g. 0x12, 0xAF, into a displayable hexadecimal string (separated by spaces), e.g. "12 AF"
    ///
    /// - Parameter data: Data to convert
    /// - Returns: String; string containing the hexadecimal display values of the entered data
    static func dataToHexString(data: Data) -> String {
        let hexDigits = Array("0123456789ABCDEF".utf16)
        var chars: [unichar] = []
        
        chars.reserveCapacity(3 * data.count)
        for byte in data {
            chars.append(hexDigits[Int(byte / 16)])
            chars.append(hexDigits[Int(byte % 16)])
            chars.append(contentsOf: " ".utf16)
        }
        return String(utf16CodeUnits: chars, count: chars.count)
    }
    
    /// Converts a entered hexadecimal string, e.g. "12 AF "..., into Data (no checking is performed)
    ///
    /// - Parameter hexString: String holding hexadecimal display values (with or without spaces)
    /// - Returns: Data holding the hexadecimal values
    static func hexStringToData(hexString: String) -> Data {
        let noSpacesHex = hexString.replacingOccurrences(of: " ", with: "")
        let len = noSpacesHex.count / 2
        var data = Data(capacity: len)
        
        for index in 0..<len {
            let j = noSpacesHex.index(noSpacesHex.startIndex, offsetBy: index*2)
            let k = noSpacesHex.index(j, offsetBy: 2)
            let bytes = noSpacesHex[j..<k]
            if var num = UInt8(bytes, radix: 16) {
                data.append(&num, count: 1)
            }
        }
        return data
    }
}
