//
// Created by 46944 on 25-3-28.
//

#include "mtext_block.h"

#include "font/font_system.h"

void mtext_block::setup_widget(const text_block_args& in_args) {
	text_ = in_args.text();
	font_ = in_args.font();
	font_size_ = in_args.font_size();
	line_spacing_ = in_args.line_spacing();
	warp_text_ = in_args.warp_text();
	update_no_wrap_size();
}

void mtext_block::on_paint(mirage_paint_context& in_context) {
	// 绘制文本
	in_context.drawer().make_text(
		layout_,
		{0, 0},
		in_context.geo().get_local_size(),
		in_context.geo()
	);
}

auto mtext_block::compute_desired_size(float in_layout_scale_multiplier) const -> Eigen::Vector2f {
	return no_warp_size_.cwiseMax(layout_.total_size);
}

void mtext_block::arrange_children(const geometry_t& in_allotted_geometry) {
	mleaf_widget<text_block_args>::arrange_children(in_allotted_geometry);
	if (warp_text_) {
		const auto current_width = in_allotted_geometry.get_local_size().x();
		if (current_width != layout_.total_size.x()) {
			layout_ = font_manager::instance().layout_text(text_, font_, font_size_, current_width, line_spacing_);
			invalidate(invalidate_reason::layout);
		}
	} else {
		layout_ = font_manager::instance().layout_text(text_, font_, font_size_, 0, line_spacing_);
		invalidate(invalidate_reason::layout);
	}
}

void mtext_block::update_no_wrap_size() {
	no_warp_size_ = font_manager::instance().layout_text(text_, font_, font_size_, 0, line_spacing_).total_size;
	invalidate(invalidate_reason::layout);
}
