use crate::{
	components::{button, tooltip, Component},
	drawing::Color,
	i18n::Translation,
	layout::WidgetID,
	parser::{
		parse_check_f32, parse_check_i32, parse_children, print_invalid_attrib, process_component,
		style::{parse_color_opt, parse_round, parse_style, parse_text_style},
		AttribPair, ParserContext, ParserFile,
	},
	widget::util::WLength,
};

pub fn parse_component_button<'a>(
	file: &'a ParserFile,
	ctx: &mut ParserContext,
	node: roxmltree::Node<'a, 'a>,
	parent_id: WidgetID,
	attribs: &[AttribPair],
) -> anyhow::Result<WidgetID> {
	let mut color: Option<Color> = None;
	let mut border = 2.0;
	let mut border_color: Option<Color> = None;
	let mut hover_color: Option<Color> = None;
	let mut hover_border_color: Option<Color> = None;
	let mut round = WLength::Units(4.0);
	let mut tooltip: Option<String> = None;
	let mut tooltip_side: Option<tooltip::TooltipSide> = None;
	let mut sticky: bool = false;

	let mut translation: Option<Translation> = None;

	let text_style = parse_text_style(attribs);
	let style = parse_style(attribs);

	for pair in attribs {
		let (key, value) = (pair.attrib.as_ref(), pair.value.as_ref());
		match key {
			"text" => {
				translation = Some(Translation::from_raw_text(value));
			}
			"translation" => {
				translation = Some(Translation::from_translation_key(value));
			}
			"round" => {
				parse_round(value, &mut round);
			}
			"color" => {
				parse_color_opt(value, &mut color);
			}
			"border" => {
				parse_check_f32(value, &mut border);
			}
			"border_color" => {
				parse_color_opt(value, &mut border_color);
			}
			"hover_color" => {
				parse_color_opt(value, &mut hover_color);
			}
			"hover_border_color" => {
				parse_color_opt(value, &mut hover_border_color);
			}
			"tooltip" => tooltip = Some(String::from(value)),
			"tooltip_side" => {
				tooltip_side = match value {
					"left" => Some(tooltip::TooltipSide::Left),
					"right" => Some(tooltip::TooltipSide::Right),
					"top" => Some(tooltip::TooltipSide::Top),
					"bottom" => Some(tooltip::TooltipSide::Bottom),
					_ => {
						print_invalid_attrib(key, value);
						None
					}
				}
			}
			"sticky" => {
				let mut sticky_i32 = 0;
				sticky = parse_check_i32(value, &mut sticky_i32) && sticky_i32 == 1;
			}
			_ => {}
		}
	}

	let (widget, component) = button::construct(
		&mut ctx.get_construct_essentials(parent_id),
		button::Params {
			color,
			border,
			border_color,
			hover_border_color,
			hover_color,
			text: translation,
			style,
			text_style,
			round,
			tooltip: tooltip.map(|t| tooltip::TooltipInfo {
				side: tooltip_side.map_or(tooltip::TooltipSide::Bottom, |f| f),
				text: Translation::from_translation_key(&t),
			}),
			sticky,
		},
	)?;

	process_component(ctx, Component(component), widget.id, attribs);
	parse_children(file, ctx, node, widget.id)?;

	Ok(widget.id)
}
