use crate::figline::FIGline;
use figfont::FIGfont;
use std::{fmt::Display, rc::Rc};
#[derive(Debug, Default)]
pub struct Options {
max_width: Option<usize>,
}
impl Options {
pub fn max_width(self, max_width: Option<usize>) -> Self {
Self {
max_width,
}
}
}
#[derive(Debug)]
pub struct FIGure {
font: Rc<FIGfont>,
lines: Vec<FIGline>,
}
impl FIGure {
pub fn new(text: &str, font: FIGfont, options: Options) -> Self {
let mut new = Self::empty(font);
for line in text.lines() {
if let Some(max) = options.max_width {
let mut fline = FIGline::empty(new.font.clone());
for word in line.split_whitespace() {
let mut test = fline.clone();
if fline.is_empty() {
test.push_str(word);
} else {
test.push_str(&format!(" {word}"));
}
if test.width() > max {
if !fline.is_empty() {
new.push_line(fline);
}
fline = FIGline::new(word, new.font.clone())
} else {
fline = test;
}
}
if !fline.is_empty() {
new.push_line(fline);
}
} else {
let line = FIGline::new(line, new.font.clone());
new.push_line(line);
}
}
new
}
pub fn from_text(text: &str) -> Self {
Self::new(text, FIGfont::standard().unwrap(), Options::default())
}
fn empty(font: FIGfont) -> Self {
Self {
font: Rc::new(font),
lines: vec![],
}
}
fn push_line(&mut self, line: FIGline) {
self.lines.push(line);
}
}
impl Display for FIGure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for line in &self.lines {
writeln!(f, "{}", line)?;
}
Ok(())
}
}