// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use egui::{Color32, TextFormat, FontId, text::LayoutJob};

pub struct LayoutJobHelper {
	font_id: FontId,
	opacity: f32,
	layout_job: LayoutJob,
	indentation: f32,
}

impl LayoutJobHelper {
	pub fn new(font_size: f32) -> LayoutJobHelper {
		LayoutJobHelper::with_font_id(FontId::proportional(font_size))
	}

	pub fn with_font_id(font_id: FontId) -> LayoutJobHelper {
		LayoutJobHelper {
			font_id,
			opacity: 1.0,
			layout_job: LayoutJob::default(),
			indentation: 0.0,
		}
	}

	pub fn add(mut self, text: &str, mut colour: Color32) -> LayoutJobHelper {
		colour = Color32::from_rgba_unmultiplied(colour.r(), colour.g(), colour.b(), (colour.a() as f32 * self.opacity).round() as u8);
		self.layout_job.append(text, self.indentation, TextFormat {
			font_id: self.font_id.clone(),
			color: colour,
			.. Default::default()
		});
		self
	}

	/**
	 * Efficiently adds a newline to the text. Panics if `add` hasn't been
	 * called.
	 */
	pub fn newline(mut self) -> LayoutJobHelper {
		self.layout_job.text.push('\n');
		self.layout_job.sections.last_mut().expect("should call `add` first").byte_range.end += 1;
		self
	}

	pub fn width(mut self, width: f32) -> LayoutJobHelper {
		self.layout_job.wrap.max_width = width;
		self
	}

	pub fn opacity(mut self, opacity: f32) -> LayoutJobHelper {
		self.opacity = opacity;
		self
	}

	pub fn indent(mut self, indentation: f32) -> LayoutJobHelper {
		self.indentation = indentation;
		self
	}

	pub fn build(self) -> LayoutJob {
		self.layout_job
	}
}
