/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2026 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.slaves.blastresistance;

import com.google.common.util.concurrent.AtomicDouble;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.world.block.BlockState;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.command.SWCommand;
import de.steamwar.linkage.Linked;
import org.bukkit.Material;
import org.bukkit.entity.Player;

import java.util.concurrent.atomic.AtomicInteger;

@Linked
public class BlastResistanceCommand extends SWCommand {

    public BlastResistanceCommand() {
        super("blastresistance");
    }

    @Register(description = "BLASTRESISTANCE_HELP")
    public void command(@Validator Player player) {
        LocalSession localSession = WorldEdit.getInstance().getSessionManager().get(BukkitAdapter.adapt(player));
        Clipboard clipboard;
        try {
            clipboard = localSession.getClipboard().getClipboards().getFirst();
        } catch (WorldEditException e) {
            BauSystem.MESSAGE.send("BLASTRESISTANCE_NO_CLIPBOARD", player);
            return;
        }

        AtomicDouble min = new AtomicDouble(0);
        AtomicDouble max = new AtomicDouble(0);
        AtomicDouble sum = new AtomicDouble(0);
        AtomicInteger count = new AtomicInteger(0);
        clipboard.forEach(blockVector3 -> {
            BlockState blockState = clipboard.getBlock(blockVector3);
            Material material = BukkitAdapter.adapt(blockState).getMaterial();
            if (material == Material.WATER || material == Material.LAVA) return;
            double blastResistance = BukkitAdapter.adapt(blockState).getMaterial().getBlastResistance();
            min.set(Math.min(min.get(), blastResistance));
            max.set(Math.max(max.get(), blastResistance));
            sum.addAndGet(blastResistance);
            count.getAndIncrement();
        });

        BauSystem.MESSAGE.send("BLASTRESISTANCE_RESULT", player, min.get(), max.get(), sum.get() / count.get());
    }
}
