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 elw, final ResourceLocation uh, final String string) {
        this.prefix = string;
        this.textureAtlas = new TextureAtlas(uh);
        elw.register(this.textureAtlas.location(), this.textureAtlas);
    }
    
    protected abstract Stream<ResourceLocation> getResourcesToLoad();
    
    protected TextureAtlasSprite getSprite(final ResourceLocation uh) {
        return this.textureAtlas.getSprite(this.resolveLocation(uh));
    }
    
    private ResourceLocation resolveLocation(final ResourceLocation uh) {
        return new ResourceLocation(uh.getNamespace(), this.prefix + "/" + uh.getPath());
    }
    
    @Override
    protected TextureAtlas.Preparations prepare(final ResourceManager abc, final ProfilerFiller ami) {
        ami.startTick();
        ami.push("stitching");
        final TextureAtlas.Preparations a4 = this.textureAtlas.prepareToStitch(abc, this.getResourcesToLoad().<ResourceLocation>map(this::resolveLocation), ami, 0);
        ami.pop();
        ami.endTick();
        return a4;
    }
    
    @Override
    protected void apply(final TextureAtlas.Preparations a, final ResourceManager abc, final ProfilerFiller ami) {
        ami.startTick();
        ami.push("upload");
        this.textureAtlas.reload(a);
        ami.pop();
        ami.endTick();
    }
    
    @Override
    public void close() {
        this.textureAtlas.clearTextureData();
    }
}
