use super::*;
use std::fs::File;
use std::io::BufReader;

pub struct FileSystemKeyProvider {
  private_key: rustls::pki_types::PrivatePkcs8KeyDer<'static>,
  certificates: Vec<rustls::pki_types::CertificateDer<'static>>,
}

impl FileSystemKeyProvider {
  pub fn new(key_path: &str,cert_path: &str)->anyhow::Result<Box<dyn KeyProvider>> {
    let certificates =
      rustls_pemfile::certs(&mut BufReader::new(&mut File::open(cert_path)?))
    .into_iter()
    .filter_map(|x| x.ok())
    .collect::<Vec<_>>();
    
    let private_key = rustls_pemfile::pkcs8_private_keys(&mut BufReader::new(
        &mut File::open(key_path)?,
    ))
    .filter_map(|x| x.ok())
    .next();
    if private_key.is_none() {
        return Err(anyhow::anyhow!(
            "No valid key found in {}",
            key_path
        ));
    }
    let private_key = private_key.unwrap();
    //let hashed_key = digest::digest(&digest::SHA256, private_key.secret_pkcs8_der());
    
    Ok(Box::new(Self {
      private_key,
      certificates,
    }))
  }
}

impl KeyProvider for FileSystemKeyProvider {
  fn get_private_key(&self)->&'_ rustls::pki_types::PrivatePkcs8KeyDer<'static> {
    &self.private_key
  }
  fn get_certificates(&self)->&'_ Vec<rustls::pki_types::CertificateDer<'static>> {
    &self.certificates
  }
} 