package us.crast.mondochest;

import java.util.HashMap;
import java.util.Map;

import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.util.BlockVector;

import us.crast.mondochest.persist.BankManager;
import us.crast.mondochest.persist.WorldCache;

public class RedstoneListener implements Listener, WorldCache.ClearWatcher {
    private BankManager bankManager;
    private Map<String, Map<BlockVector, BankSet>> bankInfo = new HashMap<String, Map<BlockVector, BankSet>>();
    
    public RedstoneListener(final MondoChest plugin) {
        this.bankManager = plugin.getBankManager();
    }
    
    @EventHandler(ignoreCancelled=true)
    public void onBlockRedstone(BlockRedstoneEvent event) {
        if (event.getOldCurrent() != 0 || event.getNewCurrent() == 0) {
            return;
        }
        Block block = event.getBlock();
        String worldName = block.getWorld().getName();
        Map<BlockVector, BankSet> worldInteresting = bankInfo.get(worldName);
        if (worldInteresting == null) {
            worldInteresting = buildWorldInteresting(worldName);
            bankInfo.put(worldName, worldInteresting);
        }
        BlockVector target = new BlockVector(block.getX(), block.getY(), block.getZ());
        BankSet targetBank = worldInteresting.get(target);
        if (targetBank != null) {
            targetBank.shelveItems(block.getWorld());
        }
    }

    private Map<BlockVector, BankSet> buildWorldInteresting(String worldName) {
        Map<BlockVector, BankSet> interesting = new HashMap<BlockVector, BankSet>();
        for (BankSet bank: bankManager.getWorldBanks(worldName).values()) {
            interesting.put(bank.getMasterSign(), bank);
        }
        bankManager.getWorldCache(worldName).addClearWatcher(this);
        return interesting;
    }

    @Override
    public void clear(String world) {
        bankInfo.remove(world);
    }
}

@@ -72,16 +72,41 @@
 l.Map;%0A%0A
+import org.bukkit.World;%0A
 import o
@@ -128,16 +128,16 @@
 .Block;%0A
-
 import o
@@ -753,30 +753,8 @@
 dler
-(ignoreCancelled=true)
 %0A   
@@ -960,32 +960,27 @@
         
-String
+World
  world
-Name
  = block
@@ -990,16 +990,50 @@
 tWorld()
+;%0A        String worldName = world
 .getName
@@ -1500,32 +1500,21 @@
 veItems(
-block.getW
+w
 orld
-()
 );%0A     

Clean up some calls