package net.minecraft.client.resources;

import java.util.function.Function;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import java.util.stream.Stream;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.server.packs.resources.SimplePreparableReloadListener;

public abstract class TextureAtlasHolder extends SimplePreparableReloadListener<TextureAtlas.Preparations> implements AutoCloseable {
    private final TextureAtlas textureAtlas;
    private final String prefix;
    
    public TextureAtlasHolder(final TextureManager eak, final ResourceLocation sm, final String string) {
        this.prefix = string;
        this.textureAtlas = new TextureAtlas(sm);
        eak.register(this.textureAtlas.location(), this.textureAtlas);
    }
    
    protected abstract Stream<ResourceLocation> getResourcesToLoad();
    
    protected TextureAtlasSprite getSprite(final ResourceLocation sm) {
        return this.textureAtlas.getSprite(this.resolveLocation(sm));
    }
    
    private ResourceLocation resolveLocation(final ResourceLocation sm) {
        return new ResourceLocation(sm.getNamespace(), this.prefix + "/" + sm.getPath());
    }
    
    @Override
    protected TextureAtlas.Preparations prepare(final ResourceManager zb, final ProfilerFiller aio) {
        aio.startTick();
        aio.push("stitching");
        final TextureAtlas.Preparations a4 = this.textureAtlas.prepareToStitch(zb, this.getResourcesToLoad().<ResourceLocation>map(this::resolveLocation), aio, 0);
        aio.pop();
        aio.endTick();
        return a4;
    }
    
    @Override
    protected void apply(final TextureAtlas.Preparations a, final ResourceManager zb, final ProfilerFiller aio) {
        aio.startTick();
        aio.push("upload");
        this.textureAtlas.reload(a);
        aio.pop();
        aio.endTick();
    }
    
    @Override
    public void close() {
        this.textureAtlas.clearTextureData();
    }
}
