package de.steamwar.bausystem.region;

import de.steamwar.bausystem.BauSystem;
import lombok.experimental.UtilityClass;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.function.Consumer;
import java.util.function.Function;

@UtilityClass
public class RegionUtils {

    public void actionBar(Region region, String s, Object... objects) {
        forEachInRegion(region, player -> {
            player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(BauSystem.MESSAGE.parse(s, player, objects)));
        });
    }

    public void message(Region region, String s, Object... objects) {
        forEachInRegion(region, player -> BauSystem.MESSAGE.send(s, player, objects));
    }

    public void message(Region region, Function<Player, String> function) {
        forEachInRegion(region, player -> {
            String message = function.apply(player);
            if (message == null) {
                return;
            }

            player.sendMessage(message);
        });
    }

    public void message(Region region, Consumer<Player> consumer) {
        forEachInRegion(region, consumer);
    }

    public void forEachInRegion(Region region, Consumer<Player> consumer) {
        Bukkit.getOnlinePlayers()
                .stream()
                .filter(player -> region.inRegion(player.getLocation()))
                .filter(player -> !region.getType().isGlobal() || Region.getRegion(player.getLocation()).getType().isGlobal())
                .forEach(consumer);
    }
}
