use io;
use unix::tty;
use tui;
use tui::widget;
use strings;

export type text = struct {
	widget: widget::widget,
	txt: str,
	style: *style,
};

export def DEFAULTSTYLE = style {
	style = void,
	normal = widget::color::DEFAULTFG,
};

export type style = struct {
	style: (void | *widget::style),
	normal: widget::color,
};

export fn newtext(state: *tui::tui, txt: str, pos: widget::coords, style: *style) text = {
	return text {
		widget = widget::widget {
			state = state,
			print = &printtext,
			resize = &resizetext,
			finish = &finishtext,
			pos = pos,
			sz = void,
			style = style.style,
			damage = widget::damageall,
			...
		},
		txt = txt,
		style = style,
	};
};

fn printtext(widget: *widget::widget) void = {
	const widget = widget: *text;
	widget.widget.buf = widget::linesbuf {
		lines = [widget.txt],
		styles = &styles,
		...
	};
	widget::print(widget);
};

fn resizetext(widget: *widget::widget, ttysize: tty::ttysize) void = {
	return;
};

export fn settext(text: *text, txt: str) void = {
	text.txt = txt;
};

fn finishtext(widget: *widget::widget) void = {
	widget::finish(widget);
};

fn styles(widget: *widget::widget, txt: str, idx: size) str = {
	const txtw = widget: *text;
	const s = widget::color_to_str(txtw.style.normal);
	defer free(s);
	return strings::concat(s, txt, "\x1B[0m");
};
