package de.steamwar.tntleague.inventory

import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryCloseEvent
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryHolder
import org.bukkit.inventory.ItemStack

abstract class SWInventoryHolder: InventoryHolder {

    val _inventory: Inventory by lazy { createInventory() }

    private val callbacks = mutableMapOf<Int, (event: InventoryClickEvent) -> Unit>()

    override fun getInventory(): Inventory = _inventory

    abstract fun createInventory(): Inventory

    open fun handleInventoryClick(event: InventoryClickEvent) {
        callbacks[event.slot]?.invoke(event)
    }

    fun addItem(item: ItemStack, slot: Int, callback: (event: InventoryClickEvent) -> Unit) {
        _inventory.setItem(slot, item)
        addCallback(slot, callback)
    }

    fun addCallback(slot: Int, callback: (event: InventoryClickEvent) -> Unit) {
        callbacks[slot] = callback
    }

    open fun handleClose(event: InventoryCloseEvent) { }

    operator fun set(slot: Int, item: Pair<ItemStack, (event: InventoryClickEvent) -> Unit>) {
        addItem(item.first, slot, item.second)
    }

    operator fun set(slot: Int, item: ItemStack) {
        addItem(item, slot) { }
    }
}