package com.namelessmc.plugin.oldbukkit;

import com.namelessmc.plugin.bukkit.BukkitNamelessPlugin;
import com.namelessmc.plugin.common.audiences.AbstractAudienceProvider;
import com.namelessmc.plugin.common.audiences.NamelessConsole;
import com.namelessmc.plugin.common.audiences.NamelessPlayer;
import net.kyori.adventure.audience.Audience;
import org.apache.commons.lang.NotImplementedException;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

public class OldBukkitAudienceProvider extends AbstractAudienceProvider {

	private void dispatchCommand(final @NonNull String command) {
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
	}

	@Override
	public @NonNull NamelessConsole console() {
		return new NamelessConsole(new LegacyCommandSenderAudience(Bukkit.getConsoleSender()), this::dispatchCommand);
	}

	@Override
	public @NonNull Audience broadcast() {
		throw new NotImplementedException(); // TODO
	}

	public @Nullable NamelessPlayer bukkitToNamelessPlayer(final Player bukkitPlayer) {
		return bukkitPlayer == null
				? null
				: new NamelessPlayer(new LegacyCommandSenderAudience(bukkitPlayer), bukkitPlayer.getUniqueId(), bukkitPlayer.getName());
	}

	@Override
	public @Nullable NamelessPlayer player(@NonNull UUID uuid) {
		for (Player player : Bukkit.getOnlinePlayers()) {
			if (player.getUniqueId().equals(uuid)) {
				return bukkitToNamelessPlayer(player);
			}
		}
		return null;
	}

	@Override
	public @Nullable NamelessPlayer playerByUsername(String username) {
		return bukkitToNamelessPlayer(Bukkit.getPlayerExact(username));
	}

	@Override
	public @NonNull Collection<@NonNull NamelessPlayer> onlinePlayers() {
		return Arrays.stream(Bukkit.getOnlinePlayers())
				.map(p -> new NamelessPlayer(new LegacyCommandSenderAudience(p), p.getUniqueId(), p.getName()))
				.collect(Collectors.toUnmodifiableList());
	}
}

@@ -592,66 +592,9 @@
 til.
-Arrays;%0Aimport java.util.Collection;%0Aimport java.util.UUID
+*
 ;%0Aim
@@ -1028,86 +1028,387 @@
 lic 
-@NonNull Audience broadcast() %7B%0A%09%09throw new NotImplementedException(); // TODO
+Audience broadcast() %7B%0A%09%09final Player%5B%5D bukkitPlayers = Bukkit.getOnlinePlayers();%0A%09%09final List%3CAudience%3E audiences = new ArrayList%3C%3E(bukkitPlayers.length + 1);%0A%09%09for (Player player : bukkitPlayers) %7B%0A%09%09%09audiences.add(new LegacyCommandSenderAudience(player));%0A%09%09%7D%0A%09%09audiences.add(new LegacyCommandSenderAudience(Bukkit.getConsoleSender()));%0A%09%09return Audience.audience(audiences);
 %0A%09%7D%0A

Implement broadcast audience