"""队列管理命令: rmqadm queues <subcommand>"""

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


class QueuesCommands:
    """管理 RabbitMQ 队列"""

    _LIST_COLUMNS = ["name", "vhost", "type", "durable", "auto_delete", "state", "messages", "consumers"]

    def __init__(self, client: RabbitMQClient, default_vhost: str = "/"):
        self._client = client
        self._default_vhost = default_vhost

    def list(self, vhost: str = None, format: str = "table"):
        """列出队列

        Args:
            vhost:  指定 vhost，不填则列出所有 vhost 的队列
            format: 输出格式，table 或 json（默认 table）
        """
        if vhost:
            path = f"/queues/{self._client.encode_name(vhost)}"
        else:
            path = "/queues"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            print_table(data, columns=self._LIST_COLUMNS)

    def show(self, name: str, vhost: str = None, format: str = "table"):
        """显示队列详情

        Args:
            name:   队列名称
            vhost:  vhost 名称（默认使用全局 --vhost 参数）
            format: 输出格式，table 或 json（默认 table）
        """
        vhost = vhost or self._default_vhost
        path = f"/queues/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            print_table([data], columns=self._LIST_COLUMNS)

    def create(self, name: str, vhost: str = None, durable: bool = True,
               auto_delete: bool = False, queue_type: str = "classic",
               max_length: int = None, message_ttl: int = None):
        """创建队列

        Args:
            name:        队列名称
            vhost:       vhost 名称（默认 /）
            durable:     是否持久化（默认 True）
            auto_delete: 无消费者时是否自动删除（默认 False）
            queue_type:  队列类型 classic/quorum/stream（默认 classic）
            max_length:  最大消息数量
            message_ttl: 消息 TTL（毫秒）
        """
        vhost = vhost or self._default_vhost
        arguments = {}
        if max_length is not None:
            arguments["x-max-length"] = max_length
        if message_ttl is not None:
            arguments["x-message-ttl"] = message_ttl
        if queue_type != "classic":
            arguments["x-queue-type"] = queue_type

        body = {
            "durable": durable,
            "auto_delete": auto_delete,
            "arguments": arguments,
        }
        path = f"/queues/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.put(path, body)
        print(f"Queue '{name}' in vhost '{vhost}' created.")

    def delete(self, name: str, vhost: str = None, if_empty: bool = False, if_unused: bool = False):
        """删除队列

        Args:
            name:      队列名称
            vhost:     vhost 名称（默认 /）
            if_empty:  仅在队列为空时删除
            if_unused: 仅在队列无消费者时删除
        """
        vhost = vhost or self._default_vhost
        path = f"/queues/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        params = {}
        if if_empty:
            params["if-empty"] = "true"
        if if_unused:
            params["if-unused"] = "true"
        # requests 的 delete 不支持 params via path，改用 query string
        if params:
            qs = "&".join(f"{k}={v}" for k, v in params.items())
            path = f"{path}?{qs}"
        self._client.delete(path)
        print(f"Queue '{name}' in vhost '{vhost}' deleted.")

    def purge(self, name: str, vhost: str = None):
        """清空队列中所有消息

        Args:
            name:  队列名称
            vhost: vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        path = f"/queues/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}/contents"
        self._client.delete(path)
        print(f"Queue '{name}' in vhost '{vhost}' purged.")
