from threading import Lock

from systools import sys_log_error
from typing import Dict

user_lock = {}  # type: Dict[str, Lock]
management_lock = Lock()


def acquire_user_lock(
    user_id,    # type: str
):
    # type: (...) -> bool

    if user_id not in user_lock:
        user_lock[user_id] = Lock()

    with management_lock:
        already_locked = user_lock[user_id].locked()
        if already_locked:
            return False

        user_lock[user_id].acquire()
        return True


def release_user_lock(
    user_id,    # type: str
):
    # type: (...) -> None

    with management_lock:
        if user_id not in user_lock or not user_lock[user_id].locked():
            sys_log_error("User lock not found for user_id: {}".format(user_id))
            return
        user_lock[user_id].release()
