use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use sha1::{Digest, Sha1};

/// 解码
pub fn decode(input: &str) -> Result<Vec<u8>, String> {
    // Base64 字符集
    let base64_chars = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    // 创建一个输出缓冲区
    let mut output = Vec::new();
    let mut buffer = [0u8; 4];
    let mut buffer_len = 0;

    // 迭代输入字符串的字节
    for byte in input.bytes() {
        if byte == b'=' {
            // 如果遇到填充字符，不增加 buffer_len，因为填充不需要转换
            break;
        } else if let Some(pos) = base64_chars.iter().position(|&b| b == byte) {
            // 将 Base64 字符转换为其对应的 6 位值
            buffer[buffer_len] = u8::try_from(pos).unwrap();
            buffer_len += 1;
        } else {
            // 如果字符不在 Base64 字符集内，返回错误
            return Err(format!("Invalid Base64 character: {}", byte as char));
        }
        // 当缓冲区满时，解码为字节
        if buffer_len == 4 {
            output.push((buffer[0] << 2) | (buffer[1] >> 4));
            output.push((buffer[1] << 4) | (buffer[2] >> 2));
            output.push((buffer[2] << 6) | buffer[3]);
            buffer_len = 0;
        }
    }

    // 处理剩余部分，不足4个字符的情况
    if buffer_len > 1 {
        output.push((buffer[0] << 2) | (buffer[1] >> 4));
    }
    if buffer_len > 2 {
        output.push((buffer[1] << 4) | (buffer[2] >> 2));
    }

    Ok(output)
}

pub fn sha_1(data: &str) -> Vec<u8> {
    let mut hasher = Sha1::new();
    hasher.update(data);
    let result = hasher.finalize();
    result.as_slice().to_vec()
}
use sha2::Sha256;
pub fn sha_256(data: Vec<u8>) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let result = hasher.finalize();
    format!("{result:x}")
}
/// 文件加密
pub fn encode_file(string: Vec<u8>) -> String {
    STANDARD.encode(string)
}
