use anyhow::Result;
use std::{collections::HashMap, convert::TryInto, fs::File, io::Read, path::Path};

use super::Previewable;

pub struct TextPath<'a>(pub &'a Path);

const PREVIEW_SIZE: usize = 1024;

impl<'a> Previewable for TextPath<'a> {
    fn get_thumbnail(&self, _options: HashMap<String, String>) -> Result<Option<Vec<u8>>> {
        let mut file = File::open(self.0)?;
        let size: usize = file.metadata()?.len().try_into()?;
        if size > PREVIEW_SIZE {
            let mut buffer = vec![0u8; PREVIEW_SIZE];
            file.read_exact(&mut buffer)?;
            Ok(Some(buffer))
        } else {
            Ok(None)
        }
    }
}
