package study.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 真实 RabbitMQ 4.4.0 broker 的连接工厂。broker 由 run.py 启动（本机独立 node，
 * 端口 5679，独立 mnesia/log 目录），测试只连接 127.0.0.1，不触碰用户其他 RabbitMQ。
 */
public final class Broker {

    public static final String HOST = "127.0.0.1";
    public static final int PORT = Integer.parseInt(System.getProperty("lab.amqp.port", "5679"));

    private Broker() {
    }

    public static Connection connect() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setAutomaticRecoveryEnabled(false);
        return factory.newConnection("u58-lab");
    }

    public static void closeQuietly(Channel channel) {
        try {
            if (channel != null && channel.isOpen()) {
                channel.close();
            }
        } catch (IOException | TimeoutException ignored) {
            // 清理尽力而为
        }
    }

    public static void closeQuietly(Connection connection) {
        try {
            if (connection != null && connection.isOpen()) {
                connection.close();
            }
        } catch (IOException ignored) {
            // 清理尽力而为
        }
    }

    /** 清理本实验可能遗留的交换机与队列（定向清理，只动本实验命名空间）。 */
    public static void purge(Channel channel, String exchange, String... queues) throws IOException {
        for (String queue : queues) {
            try {
                channel.queueDelete(queue);
            } catch (IOException ignored) {
                // 不存在即跳过
            }
        }
        // 默认交换机 "" 不允许 delete（403 ACCESS_REFUSED），只清队列
        if (exchange != null && !exchange.isEmpty()) {
            try {
                channel.exchangeDelete(exchange);
            } catch (IOException ignored) {
                // 不存在即跳过
            }
        }
    }
}
