package refinedstorage.tile.externalstorage;

import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerGroup;
import mcmultipart.microblock.IMicroblock;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.items.IItemHandler;
import powercrystals.minefactoryreloaded.api.IDeepStorageUnit;
import refinedstorage.RefinedStorage;
import refinedstorage.api.network.INetworkMaster;
import refinedstorage.api.storage.IStorageProvider;
import refinedstorage.api.storage.item.IItemStorage;
import refinedstorage.inventory.ItemHandlerBasic;
import refinedstorage.tile.IStorageGui;
import refinedstorage.tile.TileMultipartNode;
import refinedstorage.tile.config.IComparable;
import refinedstorage.tile.config.IFilterable;
import refinedstorage.tile.config.IPrioritizable;
import refinedstorage.tile.data.ITileDataProducer;
import refinedstorage.tile.data.TileDataParameter;

import java.util.ArrayList;
import java.util.List;

public class TileExternalStorage extends TileMultipartNode implements IStorageProvider, IStorageGui, IComparable, IFilterable, IPrioritizable {
    public static final TileDataParameter<Integer> PRIORITY = IPrioritizable.createParameter();
    public static final TileDataParameter<Integer> COMPARE = IComparable.createParameter();
    public static final TileDataParameter<Integer> MODE = IFilterable.createParameter();

    public static final TileDataParameter<Integer> STORED = new TileDataParameter<>(DataSerializers.VARINT, 0, new ITileDataProducer<Integer, TileExternalStorage>() {
        @Override
        public Integer getValue(TileExternalStorage tile) {
            int stored = 0;

            for (ItemStorageExternal storage : tile.storages) {
                stored += storage.getStored();
            }

            return stored;
        }
    });

    public static final TileDataParameter<Integer> CAPACITY = new TileDataParameter<>(DataSerializers.VARINT, 0, new ITileDataProducer<Integer, TileExternalStorage>() {
        @Override
        public Integer getValue(TileExternalStorage tile) {
            int capacity = 0;

            for (ItemStorageExternal storage : tile.storages) {
                capacity += storage.getCapacity();
            }

            return capacity;
        }
    });

    private static final String NBT_PRIORITY = "Priority";
    private static final String NBT_COMPARE = "Compare";
    private static final String NBT_MODE = "Mode";

    private ItemHandlerBasic filters = new ItemHandlerBasic(9, this);

    private int priority = 0;
    private int compare = 0;
    private int mode = IFilterable.WHITELIST;

    private List<ItemStorageExternal> storages = new ArrayList<>();
    private int lastDrawerCount;

    public TileExternalStorage() {
        dataManager.addWatchedParameter(PRIORITY);
        dataManager.addWatchedParameter(COMPARE);
        dataManager.addWatchedParameter(MODE);
        dataManager.addWatchedParameter(STORED);
        dataManager.addWatchedParameter(CAPACITY);
    }

    @Override
    public boolean canAddMicroblock(IMicroblock microblock) {
        return !isBlockingMicroblock(microblock, getDirection());
    }

    @Override
    public int getEnergyUsage() {
        return RefinedStorage.INSTANCE.externalStorageUsage + (storages.size() * RefinedStorage.INSTANCE.externalStoragePerStorageUsage);
    }

    @Override
    public void updateNode() {
    }

    @Override
    public void onConnectionChange(INetworkMaster network, boolean state) {
        super.onConnectionChange(network, state);

        updateStorage(network);

        network.getItemStorage().rebuild();
    }

    @Override
    public void update() {
        if (!worldObj.isRemote && network != null) {
            if (ticks % (20 * 4) == 0) {
                boolean shouldRebuild = false;

                for (ItemStorageExternal storage : storages) {
                    if (storage.updateCache()) {
                        shouldRebuild = true;
                    }
                }

                if (shouldRebuild) {
                    network.getItemStorage().rebuild();
                }
            }

            if (getFacingTile() instanceof IDrawerGroup && lastDrawerCount != ((IDrawerGroup) getFacingTile()).getDrawerCount()) {
                lastDrawerCount = ((IDrawerGroup) getFacingTile()).getDrawerCount();

                updateStorage(network);
            }
        }

        super.update();
    }

    @Override
    public void read(NBTTagCompound tag) {
        super.read(tag);

        readItems(filters, 0, tag);

        if (tag.hasKey(NBT_PRIORITY)) {
            priority = tag.getInteger(NBT_PRIORITY);
        }

        if (tag.hasKey(NBT_COMPARE)) {
            compare = tag.getInteger(NBT_COMPARE);
        }

        if (tag.hasKey(NBT_MODE)) {
            mode = tag.getInteger(NBT_MODE);
        }
    }

    @Override
    public NBTTagCompound write(NBTTagCompound tag) {
        super.write(tag);

        writeItems(filters, 0, tag);

        tag.setInteger(NBT_PRIORITY, priority);
        tag.setInteger(NBT_COMPARE, compare);
        tag.setInteger(NBT_MODE, mode);

        return tag;
    }

    @Override
    public int getCompare() {
        return compare;
    }

    @Override
    public void setCompare(int compare) {
        this.compare = compare;

        markDirty();
    }

    @Override
    public int getMode() {
        return mode;
    }

    @Override
    public void setMode(int mode) {
        this.mode = mode;

        markDirty();
    }

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public void setPriority(int priority) {
        this.priority = priority;

        markDirty();
    }

    public void updateStorage(INetworkMaster network) {
        storages.clear();

        TileEntity facing = getFacingTile();

        if (facing instanceof IDrawerGroup) {
            IDrawerGroup group = (IDrawerGroup) facing;

            for (int i = 0; i < group.getDrawerCount(); ++i) {
                if (group.isDrawerEnabled(i)) {
                    storages.add(new ItemStorageDrawer(this, group.getDrawer(i)));
                }
            }
        } else if (facing instanceof IDrawer) {
            storages.add(new ItemStorageDrawer(this, (IDrawer) facing));
        } else if (facing instanceof IDeepStorageUnit) {
            storages.add(new ItemStorageDSU(this, (IDeepStorageUnit) facing));
        } else {
            IItemHandler handler = getItemHandler(facing, getDirection().getOpposite());

            if (handler != null) {
                storages.add(new ItemStorageItemHandler(this, handler));
            }
        }

        network.getItemStorage().rebuild();
    }

    @Override
    public void addItemStorages(List<IItemStorage> storages) {
        storages.addAll(this.storages);
    }

    @Override
    public String getGuiTitle() {
        return "gui.refinedstorage:external_storage";
    }

    @Override
    public TileDataParameter<Integer> getRedstoneModeParameter() {
        return REDSTONE_MODE;
    }

    @Override
    public TileDataParameter<Integer> getCompareParameter() {
        return COMPARE;
    }

    @Override
    public TileDataParameter<Integer> getFilterParameter() {
        return MODE;
    }

    @Override
    public TileDataParameter<Integer> getPriorityParameter() {
        return PRIORITY;
    }

    public int getStored() {
        return STORED.getValue();
    }

    public int getCapacity() {
        return CAPACITY.getValue();
    }

    @Override
    public IItemHandler getFilters() {
        return filters;
    }
}

@@ -7547,32 +7547,46 @@
 RIORITY;%0A    %7D%0A%0A
+    @Override%0A
     public int g
@@ -7631,32 +7631,46 @@
 Value();%0A    %7D%0A%0A
+    @Override%0A
     public int g

Fix override