package ru.dbotthepony.mc.otm.storage.powered

import ru.dbotthepony.mc.otm.capability.energy.IMatteryEnergyStorage
import ru.dbotthepony.mc.otm.storage.IStorageAcceptor
import ru.dbotthepony.mc.otm.storage.StorageStack
import java.util.function.Supplier

class PoweredStorageAcceptor<T : StorageStack<T>>(val parent: IStorageAcceptor<T>, val energy: Supplier<IMatteryEnergyStorage>) : IStorageAcceptor<T> by parent {
	override fun equals(other: Any?): Boolean {
		return other is PoweredStorageAcceptor<*> && parent == other.parent
	}

	override fun hashCode(): Int {
		return parent.hashCode()
	}

	override fun toString(): String {
		return "PoweredStorageAcceptor[$parent]"
	}

	override fun insertStack(stack: T, simulate: Boolean): T {
		val leftover = parent.insertStack(stack, true)
		if (leftover == stack) return stack

		val energy = energy.get()
		val required = storageType.energyPerInsert(stack.shrink(leftover.count))

		if (energy.extractEnergy(required, true) == required) {
			if (!simulate) {
				val leftover2 = parent.insertStack(stack, false)

				if (leftover2.count != leftover.count) {
					energy.extractEnergy(storageType.energyPerInsert(stack.shrink(leftover2.count)), false)
				} else {
					energy.extractEnergy(required, false)
				}

				return leftover2
			}

			return leftover
		}

		return stack
	}
}
