use std::{convert::TryFrom, error::Error, sync::mpsc::Sender};
use log::{debug};
use crate::{binary::{Bit, BitVec}, cli::progress::ProgressStatus, context::{Context, ContextError}};
pub trait Decoder<D> where D: Context {
fn partial_decode(&self, context: &D) -> Result<Vec<Bit>, ContextError>;
fn decode(&self, context: &mut D, progress_channel: Option<&Sender<ProgressStatus>>) -> Result<Vec<u8>, Box<dyn Error>> {
let mut secret = Vec::default();
debug!("Decoding secret from the text");
while context.load_text().is_ok() {
let mut data = self.partial_decode(&context)?;
if let Some(tx) = progress_channel {
tx.send(ProgressStatus::Step(context.get_current_text()?.len() as u64)).ok();
}
secret.append(&mut data);
}
debug!("Padding bits to byte size boundary");
while &secret.len() % 8 != 0 {
secret.push(Bit(0));
}
debug!("Converting bits to bytes");
let bit_vec: BitVec = secret.into();
let bytes: Vec<u8> = TryFrom::try_from(bit_vec)?;
Ok(bytes)
}
}