"""交换机管理命令: rmqadm exchanges <subcommand>"""

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


class ExchangesCommands:
    """管理 RabbitMQ 交换机"""

    _LIST_COLUMNS = ["name", "vhost", "type", "durable", "auto_delete", "internal"]

    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"/exchanges/{self._client.encode_name(vhost)}"
        else:
            path = "/exchanges"
        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 名称（默认 /）
            format: 输出格式，table 或 json（默认 table）
        """
        vhost = vhost or self._default_vhost
        path = f"/exchanges/{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, exchange_type: str = "direct", vhost: str = None,
               durable: bool = True, auto_delete: bool = False, internal: bool = False):
        """创建交换机

        Args:
            name:          交换机名称
            exchange_type: 类型：direct/fanout/topic/headers（默认 direct）
            vhost:         vhost 名称（默认 /）
            durable:       是否持久化（默认 True）
            auto_delete:   无绑定时是否自动删除（默认 False）
            internal:      是否为内部交换机（默认 False）
        """
        vhost = vhost or self._default_vhost
        body = {
            "type": exchange_type,
            "durable": durable,
            "auto_delete": auto_delete,
            "internal": internal,
            "arguments": {},
        }
        path = f"/exchanges/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.put(path, body)
        print(f"Exchange '{name}' in vhost '{vhost}' created.")

    def delete(self, name: str, vhost: str = None, if_unused: bool = False):
        """删除交换机

        Args:
            name:      交换机名称
            vhost:     vhost 名称（默认 /）
            if_unused: 仅在无绑定时删除
        """
        vhost = vhost or self._default_vhost
        path = f"/exchanges/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        if if_unused:
            path += "?if-unused=true"
        self._client.delete(path)
        print(f"Exchange '{name}' in vhost '{vhost}' deleted.")
