package synthas_ui

v2 :: [2]f32
rect2 :: struct {x, y, width, height: f32}
col :: [4]u8

SIZE_AUTO :: Size_Auto {}

rect_get_tl :: #force_inline proc(rect: rect2) -> v2 {return {rect.x, rect.y}}
rect_get_tr :: #force_inline proc(rect: rect2) -> v2 {return {rect.x + rect.width, rect.y}}
rect_get_br :: #force_inline proc(rect: rect2) -> v2 {return {rect.x + rect.width, rect.y + rect.height}}
rect_get_bl :: #force_inline proc(rect: rect2) -> v2 {return {rect.x, rect.y + rect.height}}
rect_get_size :: #force_inline proc(rect: rect2) -> v2 {return {rect.width, rect.height}}
rect_get_corners :: #force_inline proc(rect: rect2) -> (tl, tr, br, bl: v2) {return rect_get_tl(rect), rect_get_tr(rect), rect_get_br(rect), rect_get_bl(rect)}
rect_grow :: #force_inline proc(rect: rect2, amount: v2) -> rect2 {return {rect.x - amount.x / 2.0, rect.y - amount.y / 2.0, rect.width + amount.x, rect.height + amount.y}}

ctx: ^Context

MeasureTextProc :: proc(text: cstring, data: rawptr) -> v2

Context :: struct {
	origin: v2,
	container_count: u16,
	containers: [dynamic]int,
	container_last_element: [dynamic]int,
	elements: [dynamic]Element,
	same_line: bool,
	measure_text_callback: MeasureTextProc,
	measure_text_callback_data: rawptr,
}

CONTAINER_STACK_SIZE :: 16

ElementId :: bit_field(int) {
	container_index: u16 | 16,
	element_index: u16 | 16,
}

Element :: struct {
	area: rect2,
	id: ElementId,
	using config: ElementConfiguration,
	data: rawptr,
	type: ElementType,
	dimensions: Dimensions,
}

element_id_invalid :: proc() -> ElementId {
	return {container_index = max(u16), element_index = max(u16)}
}

ElementConfiguration :: struct {
	label: cstring,
	color: col,
	margin, padding: v2,
}

ElementType :: enum {
	Container,
	Button,
	Slider,
	InputFloat,
	Dropdown,
	Label,
	Custom0,
	Custom1,
	Custom2,
	Custom3,
	Custom4,
	Custom5,
	Custom6,
	Custom7,
	Custom8,
	Custom9,
}

@rodata element_type_input := bit_set[ElementType] {.InputFloat}

Size_Pixels :: distinct f32
Size_Percentage :: distinct f32
Size_PercentageRemainder :: distinct f32
Size_Auto :: distinct bool

Size :: union #no_nil {
	Size_Pixels,
	Size_Percentage,
	Size_PercentageRemainder,
	Size_Auto,
}

Dimensions :: struct {
	width, height: Size,
}

Axis :: enum {X, Y}

init :: proc(ctx: ^Context, element_capacity: int, measure_text_callback: MeasureTextProc, measure_text_callback_data: rawptr, allocator := context.allocator) {
	ctx.containers = make(type_of(ctx.containers), 0, CONTAINER_STACK_SIZE, allocator)
	ctx.container_last_element = make(type_of(ctx.container_last_element), 0, CONTAINER_STACK_SIZE, allocator)
	ctx.elements = make(type_of(ctx.elements), 0, element_capacity, allocator)
	ctx.measure_text_callback = measure_text_callback
	ctx.measure_text_callback_data = measure_text_callback_data
}

start :: proc(ui_context: ^Context, origin: v2, size: v2) {
	ctx = ui_context
	ctx.origin = origin
	ctx.container_count = 0
	clear(&ctx.elements)
	clear(&ctx.containers)
	clear(&ctx.container_last_element)
	append(&ctx.elements, Element{area = {**origin, **size}, type = .Container})
	append(&ctx.containers, 0)
	append(&ctx.container_last_element, -1)
}

end :: proc() -> []Element {
	assert(len(ctx.containers) < 2, "Didn't close all containers before ending UI layout mode")
	assert(len(ctx.containers) > 0, "Closed base container before ending UI layout mode")
	elements := ctx.elements[:]
	ctx = nil
	return elements[1:]
}

same_line :: proc() {
	ctx.same_line = true
}

focus_next_element :: proc(id: ElementId, elements: []Element, allowed_focus: bit_set[ElementType]) -> ElementId {
	if id == element_id_invalid() {
		return element_id_invalid()
	}
	element_index := int(id.element_index)
	for element_index < len(elements) {
		if elements[element_index].type in allowed_focus {
			return elements[element_index].id
		}
		element_index += 1
	}
	return element_id_invalid()
}

container_begin :: proc(dimensions: Dimensions, config: ElementConfiguration, data: rawptr = nil) -> ^Element {
	element := Element{config = config, type = .Container, dimensions = dimensions, data = data}
	element.area = _resolve_element_area(element, is_text = false)
	ctx.container_count += 1
	element_ref := _append_element(element)
	container_index := len(ctx.elements) - 1
	append(&ctx.containers, container_index)
	append(&ctx.container_last_element, -1)
	return element_ref
}

container_end :: proc() {
	container_index := pop(&ctx.containers)
	container := &ctx.elements[container_index]
	pop(&ctx.container_last_element)

	_, width_is_auto := container.dimensions.width.(Size_Auto)
	_, height_is_auto := container.dimensions.height.(Size_Auto)
	if width_is_auto || height_is_auto {
		br := v2{min(f32), min(f32)}
		for element in ctx.elements[container_index:] {
			element_br := rect_get_br(get_element_outer_area(element))
			br = {max(br.x, element_br.x), max(br.y, element_br.y)}
		}
		if width_is_auto {
			container.area.width = br.x - container.area.x
		}
		if height_is_auto {
			container.area.height = br.y - container.area.y
		}
	}
	ctx.same_line = false
}

assert_auto_with_pixels :: proc(dimensions: Dimensions) {
	container := _container_current()
	if _, is_auto := container.dimensions.width.(Size_Auto); is_auto {
		_, is_pixels := dimensions.width.(Size_Pixels)
		assert(is_pixels, "Any width that is not Size_Pixels is disallowed in a container using Size_Auto for width")
	}
	if _, is_auto := container.dimensions.height.(Size_Auto); is_auto {
		_, is_pixels := dimensions.height.(Size_Pixels)
		assert(is_pixels, "Any height that is not Size_Pixels is disallowed in a container using Size_Auto for height")
	}
}

element :: proc(element_type: ElementType, dimensions: Dimensions, config: ElementConfiguration, data: rawptr = nil) -> ^Element {
	assert(element_type != .Container)
	assert_auto_with_pixels(dimensions)
	element := Element{config = config, type = element_type, dimensions = dimensions, data = data}
	element.area = _resolve_element_area(element, is_text = (element.type == .Label))
	return _append_element(element)
}

get_element_outer_area :: proc(element: Element) -> rect2 {
	return rect_grow(element.area, element.margin * 2.0)
}

get_element_inner_area :: proc(element: Element) -> rect2 {
	return rect_grow(element.area, -element.padding * 2.0)
}

_append_element :: proc(element: Element) -> ^Element {
	append(&ctx.elements, element)
	element_index := len(ctx.elements) - 1
	element := &ctx.elements[element_index]
	element.id = ElementId {container_index = ctx.container_count, element_index = u16(element_index)}
	ctx.container_last_element[len(ctx.containers) - 1] = element_index
	return element
}

_resolve_element_area :: proc(element: Element, is_text: bool) -> rect2 {
	outer_position := _resolve_element_outer_position()
	if !is_text {
		outer_size := _resolve_element_outer_size(element.dimensions)
		return rect_grow(rect2{**outer_position, **outer_size}, -element.margin * 2.0)
	}
	inner_position := ctx.measure_text_callback(element.label, ctx.measure_text_callback_data)
	return {**(outer_position + element.margin), **(inner_position + element.margin)}
}

_resolve_element_outer_position :: proc() -> v2 {
	defer {ctx.same_line = false}
	if alignment_element := _element_container_previous(); alignment_element != nil {
		if ctx.same_line {
			return rect_get_tr(get_element_outer_area(alignment_element^))
		} else {
			return {
				get_element_inner_area(_container_current()^).x,
				rect_get_bl(get_element_outer_area(alignment_element^)).y
			}
		}
	}
	return rect_get_tl(get_element_inner_area(_element_previous()^))
}

_resolve_element_outer_size :: proc(dimensions: Dimensions) -> v2 {
	return {_resolve_element_outer_size_axis(dimensions.width, .X), _resolve_element_outer_size_axis(dimensions.height, .Y)}
}

_resolve_element_outer_size_axis :: proc(size: Size, axis: Axis) -> f32 {
	switch value in size {
	case Size_Pixels:
		return f32(value)
	case Size_Percentage:
		inner := get_element_inner_area(_container_current()^)
		container_size := inner.width if axis == .X else inner.height
		return container_size * f32(value)
	case Size_PercentageRemainder:
		if element := _element_container_previous(); element != nil {
			container_inner := get_element_inner_area(_container_current()^)
			last_element_outer := get_element_outer_area(element^)
			remaining_container_size: f32
			switch axis {
			case .X: remaining_container_size = container_inner.width - rect_get_tr(last_element_outer).x
			case .Y: remaining_container_size = container_inner.height - rect_get_bl(last_element_outer).y
			}
			return remaining_container_size * f32(value)
		} else {
			inner := get_element_inner_area(_container_current()^)
			container_size := inner.width if axis == .X else inner.height
			return container_size * f32(value)
		}
	case Size_Auto:
		return 0.0
	}
	unreachable()
}

_container_current :: proc() -> ^Element {
	return &ctx.elements[ctx.containers[len(ctx.containers) - 1]]
}

_element_previous :: proc() -> ^Element {
	return &ctx.elements[len(ctx.elements) - 1]
}

_element_container_previous :: proc() -> ^Element {
	if previous_index := ctx.container_last_element[len(ctx.containers) - 1]; previous_index != -1 {
		return &ctx.elements[previous_index]
	} else {
		return nil
	}
}
