package com.thebrokenrail.twine.util.inventory;

import net.minecraft.inventory.Inventories;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.collection.DefaultedList;

public class ItemInventory extends SimpleInventory {
    private final ItemStack stack;
    private boolean isLoadingOrSaving = false;

    public ItemInventory(int size, ItemStack stack) {
        super(size);
        this.stack = stack;
        load();
    }

    protected ItemStack getHolder() {
        return stack;
    }

    private void load() {
        isLoadingOrSaving = true;
        DefaultedList<ItemStack> list = DefaultedList.ofSize(size(), ItemStack.EMPTY);
        Inventories.fromTag(stack.getOrCreateTag().getCompound("BlockEntityTag"), list);
        for (int i = 0; i < size(); i++) {
            setStack(i, list.get(i));
        }
        isLoadingOrSaving = false;
    }

    private void save() {
        isLoadingOrSaving = true;
        DefaultedList<ItemStack> list = DefaultedList.ofSize(size(), ItemStack.EMPTY);
        for (int i = 0; i < size(); i++) {
            list.set(i, getStack(i).copy());
        }
        Inventories.toTag(stack.getOrCreateSubTag("BlockEntityTag"), list);
        isLoadingOrSaving = false;
    }

    @Override
    public void markDirty() {
        super.markDirty();
        if (!isLoadingOrSaving) {
            save();
        }
    }
}
