import CoreText
import Foundation
import Utilities

private let log = Logger(category: "FontLoader")

func loadCustomFonts() {
    DispatchQueue.once {
        TypographyV1.FontResource.allCases
            .map(\.rawValue)
            .forEach { registerFont(fileName: $0) }
    }
}

func registerFont(fileName: String, bundle: Bundle = Bundle.module) {
    guard let fontURL = bundle.url(forResource: fileName, withExtension: "otf") else {
        log.telemetry.assertionFailure("No font named \(fileName).otf was found in the module bundle")
        return
    }

    var error: Unmanaged<CFError>?
    CTFontManagerRegisterFontsForURL(fontURL as CFURL, .process, &error)

    if let error = error as? Error {
        log.telemetry.error(error, message: "Error loading font \(fileName).")
    }
}
