package com.thebrokenrail.herobrine.data;

import com.thebrokenrail.herobrine.HerobrineRewoven;
import com.thebrokenrail.herobrine.entity.HerobrineEntity;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.world.PersistentState;
import net.minecraft.world.World;

import java.util.UUID;

public class HerobrineData extends PersistentState {
    private UUID uuid;

    private HerobrineData() {
        super(HerobrineRewoven.NAMESPACE);
    }

    public static HerobrineData get(ServerWorld world) {
        if (world.getRegistryKey() != World.OVERWORLD) {
            world = world.getServer().getWorld(World.OVERWORLD);
        }
        assert world != null;
        return world.getPersistentStateManager().getOrCreate(HerobrineData::new, HerobrineRewoven.NAMESPACE);
    }

    public void tick(ServerWorld world) {
        if (uuid != null) {
            Entity entity = world.getEntity(uuid);
            if (entity instanceof HerobrineEntity) {
                ((HerobrineEntity) entity).dataTick();
            } else {
                uuid = null;
                markDirty();
            }
        }
    }

    public boolean set(UUID uuid) {
        if (uuid.equals(this.uuid)) {
            return false;
        } else if (this.uuid != null) {
            return true;
        } else {
            this.uuid = uuid;
            markDirty();
            return false;
        }
    }

    public HerobrineEntity get(World world) {
        return (HerobrineEntity) ((ServerWorld) world).getEntity(uuid);
    }

    @Override
    public void fromTag(CompoundTag tag) {
        if (uuid != null) {
            tag.putUuid("UUID", uuid);
        }
    }

    @Override
    public CompoundTag toTag(CompoundTag tag) {
        if (tag.contains("UUID")) {
            uuid = tag.getUuid("UUID");
        } else {
            uuid = null;
        }
        return tag;
    }
}
