use crate::modules::heat_pump::types::{
    HPSendingFrame, HeatPumpResponse, HeatPumpResponseReceiver, HeatPumpResponseSender,
    HeatPumpSender,
};
use actix_web::web::Data;
use tokio::sync::oneshot::channel;

/// Send a command to the heat pump process and wait for a response.
pub async fn request_heat_pump(
    heat_pump_tx: Data<HeatPumpSender>,
    frame: HPSendingFrame,
) -> Result<HeatPumpResponse, &'static str> {
    let (tx, rx): (HeatPumpResponseSender, HeatPumpResponseReceiver) =
        channel::<HeatPumpResponse>();

    if heat_pump_tx.send((frame, Some(tx))).await.is_err() {
        return Err("Could not send command to heat pump process.");
    }
    match tokio::time::timeout(std::time::Duration::from_secs(3), rx).await {
        Ok(result) => {
            if let Ok(result) = result {
                Ok(result)
            } else {
                Err("Could not receive response from heat pump process")
            }
        }
        Err(_) => Err("Heat pump process timed out"),
    }
}
