package ru.dbotthepony.mc.otm.capability.matter

import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.core.UUIDUtil
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import ru.dbotthepony.mc.otm.core.util.readBinaryJsonWithCodec
import ru.dbotthepony.mc.otm.core.util.writeBinaryJsonWithCodec
import java.util.*

data class PatternState(
	val id: UUID,
	val item: Item,
	val researchPercent: Double,
) {
	fun matchId(other: PatternState): Boolean {
		return other.id == id
	}

	fun stack(count: Int = 1): ItemStack {
		return ItemStack(item, count)
	}

	fun write(buff: FriendlyByteBuf) {
		buff.writeBinaryJsonWithCodec(CODEC, this)
	}

	companion object {
		fun read(buff: FriendlyByteBuf): PatternState {
			return buff.readBinaryJsonWithCodec(CODEC)
		}

		val CODEC: Codec<PatternState> by lazy {
			RecordCodecBuilder.create {
				it.group(
					UUIDUtil.CODEC.fieldOf("id").forGetter(PatternState::id),
					BuiltInRegistries.ITEM.byNameCodec().fieldOf("item").forGetter(PatternState::item),
					Codec.doubleRange(0.0, 1.0).fieldOf("researchPercent").forGetter(PatternState::researchPercent)
				).apply(it, ::PatternState)
			}
		}
	}
}
