// r8r: rust port of n8n.io
// Initial author: Michael Cochran <mcochran@cochranblock.org>
// Built for: Tanner Woodrum, intended cofounder
// License: Unlicense (public domain dedication, see UNLICENSE)
//
// `wait` — sleep for a configurable duration, then pass items through.

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use std::sync::Arc;
use std::time::Duration;

pub struct WaitNode;

static META: NodeMetadata = NodeMetadata {
    name: "wait",
    display_name: "Wait",
    version: &[1],
    group: &["transform"],
    description: "Sleeps for a configured duration before passing items through",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

#[async_trait]
impl Node for WaitNode {
    fn metadata(&self) -> &'static NodeMetadata { &META }

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let dur = if let Some(secs) = ctx.node_def.parameters.get("seconds").and_then(|v| v.as_f64()) {
            Duration::from_secs_f64(secs.max(0.0))
        } else if let Some(d) = ctx.node_def.parameters.get("duration").and_then(|v| v.as_str()) {
            parse_duration(d)?
        } else {
            return Err(NodeError::MissingParameter("seconds or duration".into()));
        };
        tokio::time::sleep(dur).await;
        Ok(vec![ctx.input.clone()])
    }
}

fn parse_duration(s: &str) -> Result<Duration, NodeError> {
    let s = s.trim();
    let split_at = s.find(|c: char| c.is_ascii_alphabetic()).unwrap_or(s.len());
    let (num_part, unit) = s.split_at(split_at);
    let n: f64 = num_part.trim().parse()
        .map_err(|_| NodeError::Other(format!("wait: cannot parse number in `{}`", s)))?;
    let secs = match unit.trim() {
        "ms" => n / 1000.0,
        "" | "s" => n,
        "m" => n * 60.0,
        "h" => n * 3600.0,
        "d" => n * 86400.0,
        other => return Err(NodeError::Other(format!("wait: unknown unit `{}`", other))),
    };
    Ok(Duration::from_secs_f64(secs.max(0.0)))
}

inventory::submit! { NodeFactory::new("wait", || Arc::new(WaitNode)) }
