package com.spaceshipproject;

import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerInteractEvent;

/**
 * Empeche tout joueur autre que le proprietaire (ou un admin) de modifier les blocs
 * a l'interieur de la bounding box d'un spaceship charge.
 */
public class BlockProtectionListener implements Listener {

    private final SpaceShipProject plugin;
    private final SpaceshipManager manager;
    private final ConfigManager cfg;

    public BlockProtectionListener(SpaceShipProject plugin) {
        this.plugin = plugin;
        this.manager = plugin.getSpaceshipManager();
        this.cfg = plugin.getConfigManager();
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onBreak(BlockBreakEvent event) {
        if (denyIfNotOwner(event.getPlayer(), event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onPlace(BlockPlaceEvent event) {
        if (denyIfNotOwner(event.getPlayer(), event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onBucketEmpty(PlayerBucketEmptyEvent event) {
        if (denyIfNotOwner(event.getPlayer(), event.getBlockClicked().getRelative(event.getBlockFace()).getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onBucketFill(PlayerBucketFillEvent event) {
        if (denyIfNotOwner(event.getPlayer(), event.getBlockClicked().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onInteract(PlayerInteractEvent event) {
        Block b = event.getClickedBlock();
        if (b == null) return;
        if (denyIfNotOwner(event.getPlayer(), b.getLocation())) {
            event.setCancelled(true);
        }
    }

    private boolean denyIfNotOwner(Player player, Location loc) {
        if (loc.getWorld() == null) return false;
        SpaceshipManager.LoadedShipOwnerInfo info = manager.findShipOwnerAt(
                loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
        if (info == null) return false;
        if (info.ownerUuid().equals(player.getUniqueId())) return false;
        if (player.hasPermission("spaceship.admin")) return false;
        player.sendMessage(cfg.msgNotOwner());
        return true;
    }
}
