package net.dipselmedia.WorldProtect;
import java.util.LinkedList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
public class BlockListener implements Listener {
/** Main instance */
private Main plugin;
/** LinkedList that saves every block placed by the user */
private LinkedList<BlockState> placedBlocks;
/**
* Simple constructor
* @param plugin Instance of main class
*/
public BlockListener (Main plugin){
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
// Create the list
placedBlocks = new LinkedList<BlockState>();
}
/**
* Called when a player places a block
* @param e The event
*/
@EventHandler
public void onBlockPlace(BlockPlaceEvent e) {
// Apply the placed block to the list
placedBlocks.add(e.getBlock().getState());
}
/**
* Called when a block is being broken
* @param e The event
*/
@EventHandler
public void onBlockBreak(BlockBreakEvent e) {
// Check whether protection is on or off
if(plugin.getState()) {
Player p = e.getPlayer();
// Get the broken block
BlockState bs = e.getBlock().getState();
// Check if the list contains the block
// (i.e. the block has been paced by the user)
if(placedBlocks.contains(bs)){
placedBlocks.remove(bs);
} else {
// Get the destroyed block's material
Material oldMaterial = bs.getBlock().getType();
// Send the user a message
p.sendMessage(ChatColor.GOLD
+ "Sorry, you aren't allowed to destroy this "
+ ChatColor.YELLOW
+ oldMaterial.toString()
+ ChatColor.GOLD
+ " block!");
// Create a new Location where the old block was
int x = bs.getX();
int y = bs.getY();
int z = bs.getZ();
World world = bs.getWorld();
Location loc = new Location(world, x, y, z);
// Get the new block that is at this Location
// (should be air, as this block has just been broken)
bs = loc.getBlock().getState();
// Print some debug info to server console
System.out.println("[WorldProtect] Material before: " + bs.getType().toString());
// Set the block's Material
bs.setType(oldMaterial);
// Print some debug info to server console
System.out.println("[WorldProtect] Material afterwards: " + bs.getType().toString());
}
}
}
}