package com.ffii.core.utils

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.locks.ReentrantLock

/**
 * Single-server printer lock manager.
 *
 * Keyed by "ip:port" so all print jobs targeting the same printer are serialized,
 * preventing interleaving outputs when multiple users print concurrently.
 */
object PrinterLockManager {
    private val locks = ConcurrentHashMap<String, ReentrantLock>()

    fun <T> withLock(printerIp: String, printerPort: Int, block: () -> T): T {
        val key = "${printerIp.trim()}:$printerPort"
        val lock = locks.computeIfAbsent(key) { ReentrantLock(true) } // fair lock
        lock.lock()
        try {
            return block()
        } finally {
            lock.unlock()
        }
    }
}

