import Foundation

class MainThreadDispatcher {
    private static let TAG = "MainThreadDispatcher"
    
    /// Executes a block on the main thread. If already on main thread, executes immediately.
    static func runOnMainThread(_ block: @escaping () -> Void) {
        if Thread.isMainThread {
            BlueStackLogger.debug(tag: Self.TAG, message: "Already on main thread, execute immediately")
            block()
        } else {
            DispatchQueue.main.async {
                BlueStackLogger.debug(tag: Self.TAG, message: "Dispatch to main thread")
                block()
            }
        }
    }
    
    /// Executes a block synchronously on the main thread. Returns the result of the block execution
    static func runOnMainThreadSync<T>(_ block: @escaping () -> T) -> T {
        if Thread.isMainThread {
            BlueStackLogger.debug(tag: Self.TAG, message: "Already on main thread, execute immediately")
            return block()
        } else {
            return DispatchQueue.main.sync {
                BlueStackLogger.debug(tag: Self.TAG, message: "Dispatch synchronously to main thread")
                return block()
            }
        }
    }
} 
