/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2026 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.kotlin.ui.components

import de.steamwar.kotlin.ui.StateFlowListener
import de.steamwar.kotlin.ui.RenderMarker
import de.steamwar.kotlin.ui.RenderObject
import de.steamwar.kotlin.ui.context.GroupContext
import de.steamwar.kotlin.ui.context.RenderParent
import org.bukkit.Material
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.inventory.ItemStack

@RenderMarker
class ItemContext(val parent: RenderParent, val renderFunc: ItemContext.() -> Unit): RenderObject, StateFlowListener() {
    override fun update() {
        val oldX = x
        val oldY = y
        render()
        if (oldX != x || oldY != y) {
            parent.resetSlot(oldX, oldY)
        }
    }

    override fun destroy() {
        super.destroy()
        parent.resetSlot(x, y)
    }

    override fun render() {
        renderFunc(this)
        parent.renderItem(x, y, item, onClick)
    }

    init {
        render()
    }

    var item: ItemStack = ItemStack.of(Material.AIR)
    var onClick: (event: InventoryClickEvent) -> Unit = {}
    var x: Int = 0
    var y: Int = 0

    fun onClick(func: (event: InventoryClickEvent) -> Unit) {
        onClick = func
    }
}

fun GroupContext.item(init: ItemContext.() -> Unit) = children.add(ItemContext(this, init))
