use super::{KeyBuf, KeyType};
use blake2::Blake2b;
use hmac::Hmac;
use pbkdf2::pbkdf2;
use rand::{thread_rng, Rng};

/// A Thin utility function to initialise a union
/// keybuffer for a specific length
pub(crate) fn generate(tt: KeyType) -> KeyBuf {
    match tt {
        KeyType::Aes128 => {
            let mut k = KeyBuf { _32: [0u8; 32] };
            unsafe { thread_rng().fill(&mut k._32[..]) };
            k
        }
        KeyType::Aes256 => {
            let mut k = KeyBuf { _64: [0u8; 64] };
            unsafe { thread_rng().fill(&mut k._64[..]) };
            k
        }
    }
}

/// Use a key derivation function with inputs
pub(crate) fn expand(tt: KeyType, pw: &str, user: &str) -> KeyBuf {
    match tt {
        KeyType::Aes128 => {
            let mut k = KeyBuf { _32: [0u8; 32] };
            unsafe { pbkdf2::<Hmac<Blake2b>>(pw.as_bytes(), user.as_bytes(), 32, &mut k._32[..]) };
            k
        }
        KeyType::Aes256 => {
            let mut k = KeyBuf { _64: [0u8; 64] };
            unsafe { pbkdf2::<Hmac<Blake2b>>(pw.as_bytes(), user.as_bytes(), 64, &mut k._64[..]) };
            k
        }
    }
}
