from lms.utils.code import evaluate_code

from .rules import get_rule


def available_for_user(user, parameters: dict, formula) -> bool:
    """
    Проверяет доступ для пользователя по правилам видимости

    :param user:
    :param parameters:
    :param formula:
    :return: bool
    """
    params = {}

    try:
        for name, values in parameters.items():
            rule_name = name.split('__')[0]
            rule = get_rule(rule_name)
            if not rule:
                params[name] = False
                continue

            params[name] = rule(values)(user)

        return evaluate_code(formula, allowed_names=params.keys(), **params)

    except Exception:
        return False
