package ru.dbotthepony.kstarbound.world.api

import ru.dbotthepony.kommons.io.readVector2i
import ru.dbotthepony.kstarbound.defs.tile.NO_DUNGEON_ID
import java.io.DataInputStream

data class MutableCell(
	override val foreground: MutableTileState = MutableTileState(),
	override val background: MutableTileState = MutableTileState(),
	override val liquid: MutableLiquidState = MutableLiquidState(),

	override var dungeonId: Int = NO_DUNGEON_ID,
	override var blockBiome: Int = 0,
	override var envBiome: Int = 0,
	override var biomeTransition: Boolean = false,
) : AbstractCell() {
	fun readLegacy(stream: DataInputStream, version: Int = 419): MutableCell {
		foreground.read(stream)
		background.read(stream)
		liquid.read(stream)

		stream.skipNBytes(1) // foreground.material.value.collisionKind

		dungeonId = stream.readUnsignedShort()
		blockBiome = stream.readUnsignedByte()
		envBiome = stream.readUnsignedByte()

		if (version < 417) {
			biomeTransition = false
		} else {
			biomeTransition = stream.readBoolean()
		}

		if (version < 418) {
			stream.skipNBytes(1) // leftover
		} else {
			// TODO: root source
			if (stream.readBoolean()) {
				stream.readVector2i()
			}
		}

		return this
	}

	override fun tile(background: Boolean): MutableTileState {
		if (background)
			return this.background
		else
			return this.foreground
	}

	override fun immutable(): ImmutableCell {
		return POOL.intern(ImmutableCell(foreground.immutable(), background.immutable(), liquid.immutable(), dungeonId, blockBiome, envBiome, biomeTransition))
	}

	override fun mutable(): MutableCell {
		return this
	}
}
