use md5::{digest::Digest, Md5};
use sha1::Sha1;

use crate::utils::hex_upper;

pub struct HeadChunk {
    buffer: Vec<u8>,
    filled: usize,
}

impl HeadChunk {
    pub fn new(size: usize) -> Self {
        Self {
            buffer: vec![0u8; size],
            filled: 0,
        }
    }

    pub fn feed(&mut self, data: &[u8]) {
        if self.filled >= self.buffer.len() {
            return;
        }
        let take = (self.buffer.len() - self.filled).min(data.len());
        self.buffer[self.filled..self.filled + take].copy_from_slice(&data[..take]);
        self.filled += take;
    }

    pub fn as_slice(&self) -> &[u8] {
        &self.buffer
    }
}

pub fn calc_head_115(chunk: &[u8]) -> String {
    let mut hasher = Sha1::default();
    hasher.update(chunk);
    hex_upper(hasher.finalize())
}

pub fn calc_head_baidu(chunk: &[u8]) -> String {
    let mut hasher = Md5::default();
    hasher.update(chunk);
    hex_upper(hasher.finalize())
}
