//
//  LKFGlobal.swift
//  lkfc
//
//  Created by Alexander Holzer on 29.04.2021.
//  Copyright © 2021 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFGlobal {
    public static var current = LKFGlobal()
    
    static var semaphoreCounter : Int = 0
    
    static var semaphores = [Int:DispatchSemaphore]()
    
    private(set) public static var latestModelYear : UInt32 = 2025
    
    init () {
        semaphoreCallbackInit()
    }
    
    var createCallback : @convention(c) () -> Int =
    { () -> Int in
        let sema = DispatchSemaphore(value: 1)
        LKFGlobal.semaphoreCounter += 1
        LKFGlobal.semaphores[semaphoreCounter] = sema
        return semaphoreCounter
    }

    var enterCallback : @convention(c) (Int) -> Void =
    { (semaIndex) -> Void in
        guard let sema = LKFGlobal.semaphores[semaIndex] else {
            return
        }
        sema.wait()
    }

    var leaveCallback : @convention(c) (Int) -> Void =
    { (semaIndex) -> Void in
        guard let sema = LKFGlobal.semaphores[semaIndex] else {
            return
        }
        sema.signal()
    }

    var dropCallback : @convention(c) (Int) -> Void =
    { (semaIndex) -> Void in
        LKFGlobal.semaphores.removeValue(forKey: semaIndex)
    }

    
    func semaphoreCallbackInit () {
        LibLKF.lkf_semaphore_callbacks2 (createCallback, enterCallback, leaveCallback, dropCallback)
    }
    
    
    public func unloadMetaData () {
        LibLKF.lkf_unloadStamm()
    }
    
    public var cVersion : String {
        let versionString = UnsafeMutablePointer<CChar>.allocate(capacity:128)
        LibLKF.lkf_GetVersion2(versionString, 128)
        let v = String(cString: versionString)
        versionString.deallocate()
        return v
    }
}
