Open source Nest implementation
use std::path::PathBuf;

use libpijul::Base32;
use libpijul::Hash;

const CHANGES_DIR: &str = "changes";

pub struct Changestore {
    path: PathBuf,
}

impl Changestore {
    pub fn hash_from_string(hash: String) -> Option<Hash> {
        Hash::from_base32(hash.as_bytes())
    }

    pub fn new(repo_path: PathBuf) -> Self {
        Changestore { path: repo_path }
    }

    pub fn change_file(&self, hash: Hash) -> PathBuf {
        let mut path = self.dir().clone();
        libpijul::changestore::filesystem::push_filename(&mut path, &hash);

        path
    }

    pub fn ensure_parent_dirs(&self, hash: Hash) -> Result<(), anyhow::Error> {
        println!(
            "parent dir: {}",
            self.change_file(hash).parent().unwrap().display()
        );
        Ok(std::fs::create_dir_all(
            self.change_file(hash).parent().unwrap(),
        )?)
    }

    // Full path the the changes directory, last path elements are thus .pijul/changes
    pub fn dir(&self) -> PathBuf {
        self.path.join(CHANGES_DIR)
    }
}