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

open class GridPanel<out S : Screen> @JvmOverloads constructor(
	screen: S,
	parent: EditablePanel<*>?,
	x: Float = 0f,
	y: Float = 0f,
	width: Float,
	height: Float,
	protected var columns: Int,
	protected var rows: Int
) : EditablePanel<S>(screen, parent, x, y, width, height) {
	override fun performLayout() {
		var currentX = 0f
		var currentY = 0f
		var lineY = 0f
		var index = 0

		for (row in 0 until rows) {
			var column = 0

			while (column < columns) {
				val child = getChildren(index) ?: break

				if (child.visible && child.dock === Dock.NONE) {
					lineY = lineY.coerceAtLeast(child.height + child.dockMargin.top + child.dockMargin.bottom)
					child.setPos(currentX + child.dockMargin.left, currentY + child.dockMargin.top)
					currentX += child.width + child.dockMargin.left + child.dockMargin.right
				} else {
					column--
				}

				index++
				column++
			}

			currentY += lineY
			currentX = 0f
			lineY = 0f

			getChildren(index) ?: break
		}

		super.performLayout()
	}
}
