use crate::Settings;
use anyhow::Result;
use larian_formats::lspk::Lspk;
use std::path::{Path, PathBuf};

impl Settings {
    pub(crate) fn unpack_helper(mod_file_path: &Path, destination: Option<PathBuf>) -> Result<()> {
        let data = Lspk::from_file(mod_file_path)?;

        let prefix_dir = match destination {
            Some(unpack_dir) => {
                std::fs::create_dir_all(&unpack_dir)?;
                unpack_dir
            }
            None => "./".into(),
        };

        for file in data.files {
            let path = prefix_dir.join(file.path);

            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }

            std::fs::write(path, file.contents)?;
        }

        Ok(())
    }
}
