"""权限管理命令: rmqadm permissions <subcommand>"""

from rmqadm.client import RabbitMQClient
from rmqadm.formatter import print_table, print_json


class PermissionsCommands:
    """管理 RabbitMQ 用户权限"""

    _LIST_COLUMNS = ["vhost", "user", "configure", "write", "read"]

    def __init__(self, client: RabbitMQClient):
        self._client = client

    def list(self, format: str = "table"):
        """列出所有权限

        Args:
            format: 输出格式，table 或 json（默认 table）
        """
        data = self._client.get("/permissions")
        if format == "json":
            print_json(data)
        else:
            print_table(data, columns=self._LIST_COLUMNS)

    def show(self, user: str, vhost: str = "/", format: str = "table"):
        """显示某用户在某 vhost 的权限

        Args:
            user:   用户名
            vhost:  vhost 名称（默认 /）
            format: 输出格式，table 或 json（默认 table）
        """
        path = f"/permissions/{self._client.encode_name(vhost)}/{self._client.encode_name(user)}"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            print_table([data], columns=self._LIST_COLUMNS)

    def set(self, user: str, vhost: str = "/",
            configure: str = ".*", write: str = ".*", read: str = ".*"):
        """设置用户在 vhost 的权限

        Args:
            user:      用户名
            vhost:     vhost 名称（默认 /）
            configure: 配置权限正则（默认 .*，即全部允许）
            write:     写权限正则（默认 .*）
            read:      读权限正则（默认 .*）
        """
        path = f"/permissions/{self._client.encode_name(vhost)}/{self._client.encode_name(user)}"
        body = {"configure": configure, "write": write, "read": read}
        self._client.put(path, body)
        print(f"Permission for user '{user}' in vhost '{vhost}' set.")

    def delete(self, user: str, vhost: str = "/"):
        """删除用户在 vhost 的权限

        Args:
            user:  用户名
            vhost: vhost 名称（默认 /）
        """
        path = f"/permissions/{self._client.encode_name(vhost)}/{self._client.encode_name(user)}"
        self._client.delete(path)
        print(f"Permission for user '{user}' in vhost '{vhost}' deleted.")
