use std::cmp::min;
use std::time::Duration;

use async_amqp::LapinAsyncStdExt;
use async_std::sync::RwLock;
use async_std::task::{block_on, sleep};
use lapin::{Connection, ConnectionProperties};
use log::info;
use icee_container_rs::set;

use crate::config::CONFIG;

pub struct RabbitMq {
    conn: RwLock<Connection>,
}

/// Initialize RabbitMq connection.
/// Must be called before using consumers or publishers
pub fn init() {
    block_on(set("rabbitmq", RabbitMq::new()));
}

impl RabbitMq {
    #![allow(clippy::new_without_default)]
    pub fn new() -> Self {
        let conn = block_on(get_connection());

        RabbitMq {
            conn: RwLock::new(conn),
        }
    }

    pub fn connection(&self) -> &RwLock<Connection> {
        block_on(self.reconnect());

        &self.conn
    }

    async fn reconnect(&self) {
        let mut conn = self.conn.write().await;

        if !conn.status().connected() {
            *conn = get_connection().await;
        }
    }
}

async fn get_connection() -> Connection {
    let mut timer = 2;
    let max_timer = 30;
    let addr = &CONFIG.rabbitmq.dns;

    loop {
        info!("Connecting to rabbitmq: [{}]...", addr);

        if let Ok(conn) =
            Connection::connect(addr, ConnectionProperties::default().with_async_std()).await
        {
            info!("Connected");

            return conn;
        }

        info!("Retry in {} seconds", timer);
        sleep(Duration::from_secs(timer)).await;
        timer = min(timer + 2, max_timer);
    }
}
