import logging

import pika
import time


class MQConnection:
    """RabbitMQ连接管理类
    
    负责创建和管理RabbitMQ连接，处理连接失败的重试逻辑
    """

    def __init__(self, config):
        """初始化MQConnection
        
        Args:
            config: MQConfig对象，包含RabbitMQ连接配置
        """
        self.config = config  # 保存配置对象
        self.connection = None  # 连接对象
        self.channel = None  # 通道对象

    def connect(self):
        """创建RabbitMQ连接
        
        尝试创建连接，如果失败则自动重试
        
        Returns:
            pika.Channel: RabbitMQ通道对象
        """
        if self.connection and self.connection.is_open and self.channel.is_open:
            return self.channel

        attempts = self.config.connection_attempts
        retry_interval = self.config.retry_interval

        current_attempt = 0

        while True:
            try:
                # 创建凭证
                credentials = pika.PlainCredentials(
                    self.config.username,
                    self.config.password
                )

                # 创建连接参数
                params = pika.ConnectionParameters(
                    host=self.config.host,
                    port=self.config.port,
                    virtual_host=self.config.vhost,
                    credentials=credentials,
                    heartbeat=self.config.heartbeat,
                    blocked_connection_timeout=30,
                    connection_attempts = 3,
                    retry_delay = 2,
                )

                # 创建连接
                self.connection = pika.BlockingConnection(params)

                # 创建通道
                self.channel = self.connection.channel()

                return self.channel

            except Exception as e:
                current_attempt += 1
                logging.error("connect retry", e)

                if attempts is not None and current_attempt >= attempts:
                    raise

                time.sleep(retry_interval)  # 间隔后重试