/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.bausystem.features.region;

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.region.Region;
import de.steamwar.bausystem.region.flags.Flag;
import de.steamwar.bausystem.region.flags.FreezeMode;
import de.steamwar.bausystem.utils.ScoreboardElement;
import de.steamwar.linkage.Linked;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.type.NoteBlock;
import org.bukkit.block.data.type.Switch;
import org.bukkit.entity.EntityType;
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.*;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;

@Linked
public class FreezeListener implements Listener, ScoreboardElement {

    @EventHandler
    public void onBlockExplode(BlockExplodeEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) {
            return;
        }
        e.setCancelled(true);
        BlockState state = e.getBlock().getState();
        Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
            state.update(true, false);
        }, 1L);
    }

    @EventHandler
    public void onEntitySpawn(EntitySpawnEvent e) {
        if (Region.getRegion(e.getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) {
            return;
        }
        e.setCancelled(true);
        if (e.getEntityType() == EntityType.TNT) {
            Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
                e.getLocation().getBlock().setType(Material.TNT, false);
            }, 1L);
        }
    }

    @EventHandler
    public void onBlockCanBuild(BlockCanBuildEvent e) {
        if (!e.isBuildable()) return;
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) {
            return;
        }
        if (e.getMaterial() == Material.TNT) {
            e.setBuildable(false);
            e.getBlock().setType(Material.TNT, false);
        }
    }

    @EventHandler
    public void onEntityChangeBlock(EntityChangeBlockEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onPhysicsEvent(BlockPhysicsEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            if (e.getSourceBlock().getType() == Material.NOTE_BLOCK) {
                BlockState state = e.getSourceBlock().getState();
                NoteBlock noteBlock = (NoteBlock) state.getBlockData();
                if (noteBlock.isPowered()) {
                    Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
                        state.update(true, false);
                    }, 1);
                }
            }
            if (e.getBlock().getType() == Material.NOTE_BLOCK) {
                BlockState state = e.getBlock().getState();
                NoteBlock noteBlock = (NoteBlock) state.getBlockData();
                if (noteBlock.isPowered()) {
                    Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
                        state.update(true, false);
                    }, 1);
                }
            }
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onPistonExtend(BlockPistonExtendEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onPistonRetract(BlockPistonRetractEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onBlockGrow(BlockGrowEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onRedstoneEvent(BlockRedstoneEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setNewCurrent(e.getOldCurrent());
        }
    }

    @EventHandler
    public void onBlockDispense(BlockDispenseEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onInventoryMoveEvent(InventoryMoveItemEvent e) {
        if (e.getDestination().getLocation() != null && Region.getRegion(e.getDestination().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        } else if (e.getSource().getLocation() != null && Region.getRegion(e.getSource().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onBlockBreak(BlockBreakEvent e) {
        if (e.getPlayer().getInventory().getItemInMainHand().getType() == Material.DEBUG_STICK) return;
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
            e.getBlock().setType(Material.BARRIER, false);
            e.getBlock().setType(Material.AIR, false);
        }
    }

    /*
    @EventHandler
    public void onBlockPlace(BlockPlaceEvent e) {
        if (Core.getVersion() < 19) return;
        if (!e.getItemInHand().getType().isBlock()) return;
        if (Region.getRegion(e.getBlock().getLocation()).get(Flag.FREEZE) == FreezeMode.ACTIVE) {
            e.setCancelled(true);
            Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
                e.getBlock().setType(e.getItemInHand().getType(), false);
            }, 1L);
        }
    }
     */

    @EventHandler
    public void onFluidLevelChange(FluidLevelChangeEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onBlockSpread(BlockSpreadEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onBlockFromTo(BlockFromToEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onSpongeAbsorb(SpongeAbsorbEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onBlockForm(BlockFormEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent e) {
        if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
        if (Region.getRegion(e.getClickedBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            Block block = e.getClickedBlock();
            if (block.getType() == Material.LEVER) {
                Switch data = ((Switch) block.getBlockData());
                data.setPowered(!data.isPowered());
                block.setBlockData(data, false);
            }
        }
    }

    @EventHandler
    public void onBlockFade(BlockFadeEvent e) {
        if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
            e.setCancelled(true);
        }
    }

    @Override
    public ScoreboardGroup getGroup() {
        return ScoreboardGroup.REGION;
    }

    @Override
    public int order() {
        return 2;
    }

    @Override
    public String get(Region region, Player p) {
        if (region.getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) return null;
        return "§e" + BauSystem.MESSAGE.parse(Flag.FREEZE.getChatValue(), p) + "§8: " + BauSystem.MESSAGE.parse(region.getRegionData().get(Flag.FREEZE).getWithDefault().getChatValue(), p);
    }
}
