use std::borrow::Cow;
use ratatui::{
buffer::Buffer,
layout::Rect,
style::Style,
text::{Line, Span},
widgets::Widget,
};
use super::{
ACCENT, BAD, BAR_CHAR_LEN, BAR_ON, BOLD, COL_GAP, COL_GAP_W, DIM, FAINT, GLOW, WARN, bar_str,
dash_str,
};
use crate::{
board::Board,
i18n::T,
text::{count, eta, fit_owned, fmt_tok, percent, width},
};
const BAR_MAX: usize = 32;
const BAR_MIN: usize = 8;
const PERMILLE: usize = 1000;
pub(super) fn draw_foot(board: &Board, area: Rect, buf: &mut Buffer, w: usize) {
footer_line(board, w).render(area, buf);
}
fn footer_line(board: &Board, w: usize) -> Line<'static> {
let view = board.progress.view();
let mut tail_li = vec![
Span::raw(COL_GAP),
Span::styled(percent(&view), BOLD),
Span::raw(COL_GAP),
Span::raw(count(&view)),
];
let eta_str = eta(&view);
if !eta_str.is_empty() {
tail_li.push(Span::raw(COL_GAP));
tail_li.push(Span::styled(eta_str, DIM));
}
tail_li.push(Span::raw(COL_GAP));
tail_li.push(Span::styled(T.ui.foot_conc(board.active_conc()), ACCENT));
tail_li.push(Span::raw(COL_GAP));
tail_li.push(Span::styled(
T.ui.foot_tok(fmt_tok(board.total_tok())),
BOLD,
));
let mut tail_w: usize = tail_li.iter().map(|s| width(&s.content)).sum();
let mut push_opt = |text: Cow<'static, str>, style: Style| {
let tw = COL_GAP_W + width(&text);
if 1 + BAR_MIN + tail_w + tw <= w {
tail_w += tw;
tail_li.push(Span::raw(COL_GAP));
tail_li.push(Span::styled(text, style));
}
};
if board.fail > 0 {
push_opt(T.ui.count_fail(board.fail), BAD);
}
if board.hit > 0 {
push_opt(T.ui.count_cache(board.hit), DIM);
}
if board.retry > 0 {
push_opt(T.ui.count_retry(board.retry), WARN);
}
let bar_w = BAR_MAX.min(w.saturating_sub(1 + tail_w)).max(BAR_MIN);
let on = (usize::from(view.permille) * bar_w / PERMILLE).min(bar_w);
let body = if on < bar_w { on.saturating_sub(1) } else { on };
let mut span_li = vec![
Span::raw(" "),
Span::styled(bar_str(BAR_ON, body), ACCENT),
Span::styled(&bar_str(BAR_ON, on)[body * BAR_CHAR_LEN..], GLOW),
Span::styled(dash_str(bar_w - on), FAINT),
];
span_li.extend(tail_li);
let line = Line::from(span_li);
if line.width() <= w {
line
} else {
Line::raw(fit_owned(line.to_string(), w))
}
}