/*
 * MIT License
 *
 * Copyright (c) 2020 Azercoco & Technici4n
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package aztech.modern_industrialization.client.util;

import aztech.modern_industrialization.client.thirdparty.fabricrendering.MutableQuadView;
import aztech.modern_industrialization.client.thirdparty.fabricrendering.QuadBuffer;
import aztech.modern_industrialization.client.thirdparty.fabricrendering.QuadEmitter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.inventory.InventoryMenu;
import org.jspecify.annotations.Nullable;

public class QuadCube {
    private final ResourceLocation spriteLocation;
    private BakedQuad @Nullable [] quads;

    public QuadCube(ResourceLocation spriteLocation) {
        this.spriteLocation = spriteLocation;
    }

    public BakedQuad[] getQuads() {
        var sprite = Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(spriteLocation);
        // Rebuild quads if the sprite changed
        if (quads == null || quads[0].getSprite() != sprite) {
            quads = buildQuads(sprite);
        }
        return quads;
    }

    private static BakedQuad[] buildQuads(TextureAtlasSprite sprite) {
        var quads = new BakedQuad[6];
        for (Direction direction : Direction.values()) {
            QuadEmitter emitter = new QuadBuffer();
            emitter.square(direction, 0, 0, 1, 1, 0);
            emitter.spriteBake(sprite, MutableQuadView.BAKE_LOCK_UV);
            quads[direction.get3DDataValue()] = emitter.toBakedQuad(sprite);
        }
        return quads;
    }
}
