use crate::{step::Step, workflow::WorkflowConfig};
use serde::{Deserialize, Serialize};
use std::{env, path::PathBuf};
use tokio::fs;

#[derive(Serialize, Deserialize, Debug)]
pub struct Job {
    pub name: Option<String>,
    pub image: Option<String>,
    pub steps: Vec<Step>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JobConfig {
    pub id: String,
    pub image: String,
    pub container_working_dir: PathBuf,
    pub container_user_dir: PathBuf,
    pub workflow_config: WorkflowConfig,
}

impl Job {
    pub async fn run(&mut self, config: WorkflowConfig) -> anyhow::Result<()> {
        let job_id = "test".to_string();

        // TODO Create temp dir for job
        #[allow(deprecated)]
        let home_dir = env::home_dir().ok_or(anyhow::anyhow!("Failed to get home directory"))?;
        let working_dir = home_dir.join("runner").join(&job_id);
        let user_dir = working_dir.join("data");
        fs::create_dir_all(&user_dir).await?;

        let image = self.image.clone().unwrap_or("ubuntu".to_string());
        let config = JobConfig {
            id: job_id,
            image,
            container_working_dir: working_dir,
            container_user_dir: user_dir,
            workflow_config: config,
        };

        for step in self.steps.iter_mut() {
            if let Err(err) = step.run(config.clone()).await {
                log::error!("Step error: {}", err.to_string());
                break;
            }
        }

        fs::remove_dir_all(config.container_working_dir).await?;

        Ok(())
    }
}
