use std::time::Duration;

use actix::Addr;
use chrono::Local;
use emgauwa_lib::constants::RELAYS_RETRY_TIMEOUT;
use emgauwa_lib::errors::EmgauwaError;
use futures::pin_mut;
use tokio::time;
use tokio::time::timeout;
use utils::app_state_get_notifier;

use crate::app_state::AppState;
use crate::utils;

pub async fn run_relays_loop(app_state: Addr<AppState>) {
	log::debug!("Spawned relays loop");
	loop {
		let run_result = run_relays(&app_state).await;
		if let Err(err) = run_result {
			log::error!("Error running relays: {}", err);
		}
		time::sleep(RELAYS_RETRY_TIMEOUT).await;
	}
}

async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
	let default_duration = Duration::new(10, 0);
	let notifier = &*app_state_get_notifier(app_state).await?;

	loop {
		let notifier_future = notifier.notified();
		pin_mut!(notifier_future);
		let timeout_result = timeout(default_duration, &mut notifier_future).await;
		let changed = timeout_result.is_ok();

		log::debug!(
			"Relay loop at {} (changed: {})",
			Local::now().naive_local().time(),
			changed
		);
	}
}