package ru.dbotthepony.mc.otm.client.screen.panels.util

import net.minecraft.client.gui.screens.Screen
import ru.dbotthepony.mc.otm.client.screen.panels.Dock
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import kotlin.math.roundToInt

class HorizontalStripPanel<out S : Screen>(
	screen: S,
	parent: EditablePanel<*>?,
	x: Float = 0f,
	y: Float = 0f,
	width: Float = 0f,
	height: Float = 0f,
) : EditablePanel<S>(screen, parent, x, y, width, height) {
	override fun sizeToContents() {
		var w = 0f
		var h = 0f

		for (child in children) {
			if (child.dock == Dock.NONE) {
				w += child.width + child.dockMargin.left + child.dockMargin.right
				h = h.coerceAtLeast(child.height)
			}
		}

		width = w
		height = h
	}

	override fun performLayout() {
		super.performLayout()

		var w = 0f

		for (child in children) {
			if (child.dock == Dock.NONE) {
				w += child.width + child.dockMargin.left + child.dockMargin.right
			}
		}

		w = width / 2f - w / 2f

		for (child in children) {
			if (child.dock == Dock.NONE) {
				child.y = (height / 2f - child.height / 2f).roundToInt().toFloat()
				child.x = (w + child.dockMargin.left).roundToInt().toFloat()
				w += child.dockMargin.left + child.width + child.dockMargin.right
			}
		}
	}
}
