Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
31 kB
0
Indexable
Never
package org.lifestealsmp.lifestealcore;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.attribute.Attribute;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;

import github.scarsz.discordsrv.DiscordSRV;
import github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder;
import github.scarsz.discordsrv.dependencies.jda.api.JDA;
import github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed;
import github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;

public class main extends JavaPlugin implements Listener {

	private FileConfiguration data;
	private File dfile;

	public void onEnable() {
		Bukkit.getServer().getPluginManager().registerEvents(this, (Plugin) this);
		saveDefaultConfig();
		setupFiles();
		
		timer = new HashMap<>();
		Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
			public void run() {
				for(Player onlineplayers : Bukkit.getOnlinePlayers()) {
					if(timer.containsKey(onlineplayers)) {
						int num = timer.get(onlineplayers);
						if(num > 0) {
							timer.put(onlineplayers, num - 1);
							String actionBarMessage = "§cBoosting Detected! Blocked for §f" + timer.get(onlineplayers) / 60 + " minutes!";
							onlineplayers.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(actionBarMessage));
						} else {
							timer.remove(onlineplayers);
						}
					}
				}
			}
		}, 0, 20);
	}

	public void setupFile(File file) {
		if (!file.exists())
			try {
				file.createNewFile();
			} catch (IOException e) {
				Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create " + file.getName() + "!");
			}
	}

	public void saveFile(FileConfiguration config, File file) {
		try {
			config.save(file);
		} catch (IOException e) {
			Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save " + file.getName() + "!");
		}
	}

	public void setupFiles() {
		this.dfile = new File(getDataFolder(), "data.yml");
		setupFile(this.dfile);
		this.data = (FileConfiguration) YamlConfiguration.loadConfiguration(this.dfile);
	}

	public FileConfiguration getData() {
		return this.data;
	}

	public void saveData() {
		saveFile(this.data, this.dfile);
	}
	public void reloadData() {
		this.data = (FileConfiguration) YamlConfiguration.loadConfiguration(this.dfile);
	}
	
	@EventHandler
	public void onPlayerDeath(PlayerDeathEvent event) {
		Player player = event.getEntity();
		removeHeart(player, event.getDeathMessage());
		if (event.getEntity().getKiller() instanceof Player) {
			Player killer = event.getEntity().getKiller();
			if(timer.containsKey(killer)) {
				return;
			}
			String playerAddress = killer.getAddress().getAddress().getHostAddress();
	        String killerAddress = player.getAddress().getAddress().getHostAddress();
	        // Block same IP kill
	        if (playerAddress.equals(killerAddress)) {
	            return;
	        } 
			double currentHealth = killer.getMaxHealth();
			if (currentHealth == 40.0D) {
				ItemStack item = new ItemStack(Material.PAPER);
				ItemMeta meta = item.getItemMeta();
				meta.setDisplayName(ChatColor.GREEN + "§4Claimable Heart");
				meta.setCustomModelData(10012);
				item.setItemMeta(meta);

				Location location = player.getLocation();
				World world = player.getWorld();
				world.dropItemNaturally(location, item);
			} else {
				killer.setMaxHealth(currentHealth + 2.0D);
			}
		}
	}

	public void addHeart(Player player) {
		double currentHealth = player.getMaxHealth();
		if (currentHealth == 40.0D) {
			int num = getData().getInt(player.getName() + ".Hearts-Deposited");
			getData().set(player.getName() + ".Hearts-Deposited", Integer.valueOf(num + 1));
			saveData();
		} else {
			player.setMaxHealth(currentHealth + 2.0D);
		}
	}

	public void removeHeart(Player player, String deathMessage) {
		double currentHealth = player.getMaxHealth();
		if (currentHealth <= 2.0D) {
			deathBan(player, deathMessage);
		} else {
			player.setMaxHealth(currentHealth - 2.0D);
		}
	}

	public void deathBan(Player player, String deathMessage) {
		getData().set(player.getName() + ".Death-Reason", deathMessage);
		getData().set(player.getName() + ".Death-Banned", Boolean.valueOf(true));
		// Format the current date and set Time-Banned
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		String currentDate = dateFormat.format(new Date());
		getData().set(player.getName() + ".Time-Banned", currentDate);

		saveData();
		String kickMessage = "You have been death banned!";
		player.kickPlayer(kickMessage);
		String playerName = player.getName();
		try {
			String imageUrl = "https://mc-heads.net/player/" + playerName;
			EmbedBuilder embedBuilder = new EmbedBuilder();
			embedBuilder.setTitle(String.valueOf(playerName) + " has been death banned!!");
			String banReason = data.getString(player.getName() + ".Death-Reason");
			embedBuilder.setDescription("Death Cause: " + banReason);
			embedBuilder.setImage(imageUrl);
			embedBuilder.setColor(Color.RED);
			MessageEmbed embed = embedBuilder.build();
			JDA jda = DiscordSRV.getPlugin().getJda();
			TextChannel channel = jda.getTextChannelById("1119383259328040980");
			if (channel != null) {
				channel.sendMessageEmbeds(embed, new MessageEmbed[0]).queue(
						success -> System.out.println("Embed sent successfully!"), error -> error.printStackTrace());
			} else {
				System.out.println("Channel not found!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@EventHandler
	public void PlayerLoginEvent(PlayerLoginEvent event) {
		Player player = event.getPlayer();
		boolean deathBanned = getData().getBoolean(player.getName() + ".Death-Banned");
		if (deathBanned) {
			String kickMessage = "You have been death banned!";
			event.disallow(PlayerLoginEvent.Result.KICK_OTHER, kickMessage);
		}
	}

	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		if (command.getName().equalsIgnoreCase("LifeStealCore")) {
			if (!sender.hasPermission("LifeStealCore.Admin"))
				return true;
			if (args.length == 3 && args[0].equalsIgnoreCase("give")) {
				int amount;
				try {
					amount = Integer.parseInt(args[2]);
				} catch (NumberFormatException e) {
					sender.sendMessage(ChatColor.RED + "Invalid amount!");
					return true;
				}
				if (args[1].equalsIgnoreCase("all")) {
					for (Player player : Bukkit.getOnlinePlayers())
						adjustPlayerHealth(player, amount);
				} else {
					Player target = Bukkit.getPlayerExact(args[1]);
					if (target != null) {
						adjustPlayerHealth(target, amount);
					} else {
						sender.sendMessage(ChatColor.YELLOW + "Player not found!");
					}
				}
				return true;
			}
		}
		if (command.getName().equalsIgnoreCase("ReviveStation") && sender instanceof Player) {
			Player player = (Player) sender;
			ReviveStationInventory(player);
		}
		return false;
	}

	private void adjustPlayerHealth(Player player, int amount) {
		double currentMaxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue();
		double potentialNewMaxHealth = currentMaxHealth + (amount * 2);
		if (potentialNewMaxHealth <= 40.0D) {
			player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(potentialNewMaxHealth);
		} else {
			player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(40.0D);
			double excessHearts = (potentialNewMaxHealth - 40.0D) / 2.0D;
			double num = 0.0D;
			if (getData().contains(player.getName() + ".Hearts-Deposited"))
				num = getData().getDouble(player.getName() + ".Hearts-Deposited");
			getData().set(player.getName() + ".Hearts-Deposited", Double.valueOf(num + excessHearts));
			saveData();
		}
	}

	public void ReviveStationInventory(Player player) {
		Inventory inv = Bukkit.createInventory(null, 27, "Revive Station");
		ItemStack blank = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
		ItemMeta blankMeta = blank.getItemMeta();
		blankMeta.setDisplayName(ChatColor.AQUA + "§r");
		blankMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ENCHANTS });
		blank.setItemMeta(blankMeta);
		for (int i = 0; i < inv.getSize(); i++) {
			if (inv.getItem(i) == null)
				inv.setItem(i, blank);
		}
		ItemStack deathbans = new ItemStack(Material.PAPER);
		ItemMeta deathbansMeta = deathbans.getItemMeta();
		deathbansMeta.setDisplayName(ChatColor.YELLOW + "Death Bans");
		deathbansMeta.setCustomModelData(Integer.valueOf(10013));
		deathbansMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		deathbans.setItemMeta(deathbansMeta);


		int hearts = getData().getInt(player.getName() + ".Hearts-Deposited");
		ItemStack heartCount = new ItemStack(Material.PAPER);
		ItemMeta heartCountMeta = heartCount.getItemMeta();
		heartCountMeta.setDisplayName(ChatColor.BLUE + "" + hearts + " Hearts Deposited");
		heartCountMeta.setCustomModelData(Integer.valueOf(10012));
		heartCountMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		if (hearts == 0) {
			heartCount.setAmount(1);
		} else {
			heartCount.setAmount(getData().getInt(player.getName() + ".Hearts-Deposited"));
		}
		heartCount.setItemMeta(heartCountMeta);

		ItemStack withdrawHearts = new ItemStack(Material.PAPER);
		ItemMeta withdrawHeartsMeta = withdrawHearts.getItemMeta();
		withdrawHeartsMeta.setDisplayName(ChatColor.GOLD + "Withdraw Hearts");
		withdrawHeartsMeta.setCustomModelData(Integer.valueOf(10014));
		withdrawHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		withdrawHearts.setItemMeta(withdrawHeartsMeta);

		ItemStack depositHearts = new ItemStack(Material.PAPER);
		ItemMeta depositHeartsMeta = depositHearts.getItemMeta();
		depositHeartsMeta.setDisplayName(ChatColor.GREEN + "Deposit Hearts");
		depositHeartsMeta.setCustomModelData(Integer.valueOf(10015));
		depositHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		depositHearts.setItemMeta(depositHeartsMeta);

		inv.setItem(10, deathbans);
		inv.setItem(12, heartCount);
		inv.setItem(14, withdrawHearts);
		inv.setItem(16, depositHearts);
		player.openInventory(inv);
	}

	public void openDeathBansInventory(Player player, int page) {
		FileConfiguration data = getData();
		List<String> bannedPlayers = new ArrayList<>();

		for (String playerName : data.getKeys(false)) {
	        if (data.getBoolean(playerName + ".Death-Banned")) {
	        	bannedPlayers.add(playerName);
	        }
	    }

		Inventory inv = Bukkit.createInventory(null, 27, "Death Bans Page " + page);

		// Filling inventory with placeholder items
		ItemStack blank = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
		ItemMeta blankMeta = blank.getItemMeta();
		blankMeta.setDisplayName(ChatColor.RED + "§r");
		blankMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
		blank.setItemMeta(blankMeta);

		for (int i = 0; i < inv.getSize(); i++) {
			inv.setItem(i, blank);
		}

		// Calculate indices for pagination
		int startIndex = (page - 1) * 21;
		int endIndex = Math.min(startIndex + 21, bannedPlayers.size());

		// Set player heads in the inventory
		for (int i = startIndex; i < endIndex; i++) {
		    String playerName = bannedPlayers.get(i);
		    ItemStack head = new ItemStack(Material.PLAYER_HEAD, 1);
		    SkullMeta headMeta = (SkullMeta) head.getItemMeta();

		    OfflinePlayer offliinePlayer = Bukkit.getOfflinePlayer(playerName);
		    if (player != null) {
		        headMeta.setDisplayName("§a" + playerName); // You can change the color code as needed

		        // Set the owning player to display the correct head
		        headMeta.setOwningPlayer(offliinePlayer);

		        // Fetch the Time-Banned info
		        String timeBanned = data.getString(playerName + ".Time-Banned");
		        String banReason = data.getString(playerName + ".Death-Reason");
		        if (timeBanned != null) {
		            // Create lore and add it to the headMeta
		            List<String> lore = new ArrayList<>();
		            lore.add("§7Time Banned: §c" + timeBanned);
		            lore.add("§7Ban Reason: §c" + banReason);
		            lore.add("");
		            lore.add("§aClick to open revive menu!");
		            headMeta.setLore(lore);
		        }

		        // Apply the modified meta to the head
		        head.setItemMeta(headMeta);

		        // Place the head in the inventory
		        inv.setItem((i - startIndex), head);
		    }
		}

		// Adding previous and next page buttons
		if (page > 1) {
			ItemStack prevPage = new ItemStack(Material.ARROW);
			ItemMeta prevPageMeta = prevPage.getItemMeta();
			prevPageMeta.setDisplayName(ChatColor.GOLD + "§cPrevious Page");
			prevPage.setItemMeta(prevPageMeta);
			inv.setItem(25, prevPage); // Bottom left slot for 'previous' button
		}

		if (endIndex < bannedPlayers.size()) {
			ItemStack nextPage = new ItemStack(Material.ARROW);
			ItemMeta nextPageMeta = nextPage.getItemMeta();
			nextPageMeta.setDisplayName(ChatColor.AQUA + "§aNext Page");
			nextPage.setItemMeta(nextPageMeta);
			inv.setItem(26, nextPage); // Bottom right slot for 'next' button
		}

		player.openInventory(inv);
	}

	@EventHandler
	public void onInventoryClickTwo(InventoryClickEvent event) {
		Player player = (Player) event.getWhoClicked();
		if (event.getView().getTitle().startsWith("Death Bans")) {

			event.setCancelled(true);

			ItemStack clickedItem = event.getCurrentItem();
			if (clickedItem == null || clickedItem.getType() == Material.AIR)
				return;

			if (clickedItem.getType() == Material.PLAYER_HEAD) {
				// Extract the player's name from the skull
				SkullMeta skullMeta = (SkullMeta) clickedItem.getItemMeta();
				if (skullMeta.hasOwner()) {
					final String skullOwnerName = skullMeta.getOwningPlayer().getName();
					// Open a new inventory with the title "Name's Revive"
					openReviveInventory(player, skullOwnerName);
					return;
				}
			}

			// Existing pagination code
			String title = event.getView().getTitle();
			int currentPage = Integer.parseInt(title.split(" ")[3]);

			if (clickedItem.getType() == Material.ARROW) {
				if (clickedItem.getItemMeta().getDisplayName().contains("Previous Page")) {
					openDeathBansInventory(player, currentPage - 1);
				} else if (clickedItem.getItemMeta().getDisplayName().contains("Next Page")) {
					openDeathBansInventory(player, currentPage + 1);
				}
			}
		}
	}

	private HashMap<Player, Integer> playerScores = new HashMap<>();

	// Example method to add or update a player's score
	public void setPlayerScore(Player player, int score) {
		playerScores.put(player, score);
	}

	// Example method to get a player's score
	public Integer getPlayerScore(Player player) {
		if(playerScores.containsKey(player)) {
			return playerScores.get(player);
		} else {
			return 0;
		}
	}

	public void openReviveInventory(Player player, String playerName) {
		int totalHearts = getData().getInt(player.getName() + ".Hearts-Deposited");
		int count = getPlayerScore(player);
		Inventory inv = Bukkit.createInventory(null, 27, "[" + playerName + "] Your Hearts: " + totalHearts);

		ItemStack blank = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
		ItemMeta blankMeta = blank.getItemMeta();
		blankMeta.setDisplayName(ChatColor.AQUA + "§r");
		blankMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ENCHANTS });
		blank.setItemMeta(blankMeta);
		for (int i = 0; i < inv.getSize(); i++) {
			if (inv.getItem(i) == null)
				inv.setItem(i, blank);
		}

		ItemStack heartCount = new ItemStack(Material.PAPER);
		ItemMeta heartCountMeta = heartCount.getItemMeta();
		heartCountMeta.setDisplayName("Use " + getPlayerScore(player) + " heart(s) to revive this player!");
		heartCountMeta.setCustomModelData(Integer.valueOf(10012));
		heartCountMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		if (count == 0) {
			ItemStack zeroHearts = new ItemStack(Material.BEDROCK);
			ItemMeta zeroHeartsMeta = heartCount.getItemMeta();
			zeroHeartsMeta.setDisplayName(ChatColor.GOLD + "Add Hearts!");
			zeroHearts.setItemMeta(zeroHeartsMeta);
			inv.setItem(13, zeroHearts);
		} else {
			heartCount.setAmount(count);
			heartCount.setItemMeta(heartCountMeta);
			inv.setItem(13, heartCount);
		}

		ItemStack withdrawHearts = new ItemStack(Material.PAPER);
		ItemMeta withdrawHeartsMeta = withdrawHearts.getItemMeta();
		withdrawHeartsMeta.setDisplayName(ChatColor.GREEN + "Remove heart from revive");
		withdrawHeartsMeta.setCustomModelData(Integer.valueOf(10014));
		withdrawHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		withdrawHearts.setItemMeta(withdrawHeartsMeta);

		ItemStack depositHearts = new ItemStack(Material.PAPER);
		ItemMeta depositHeartsMeta = depositHearts.getItemMeta();
		depositHeartsMeta.setDisplayName(ChatColor.BLUE + "Add heart to revive");
		depositHeartsMeta.setCustomModelData(Integer.valueOf(10015));
		depositHeartsMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		depositHearts.setItemMeta(depositHeartsMeta);

		inv.setItem(21, withdrawHearts);
		inv.setItem(23, depositHearts);
		player.openInventory(inv);
	}

	@EventHandler
	public void onInventoryClickThree(InventoryClickEvent event) {
		Player player = (Player) event.getWhoClicked();
		if (event.getView().getTitle().contains("Your Hearts:")) {
			event.setCancelled(true);
			
			if (event.getSlot() == 13) {
				int num = getPlayerScore(player);
				if(num != 0) {
					int depositedHearts = getData().getInt(player.getName() + ".Hearts-Deposited");
					getData().set(player.getName() + ".Hearts-Deposited", depositedHearts - getPlayerScore(player));
					saveData();
					playerScores.remove(player);
					
					String inventoryTitle = event.getView().getTitle();
					String[] parts = inventoryTitle.split(" ");
					String revivedPlayerName = parts[0].substring(1, parts[0].length() - 1);
					OfflinePlayer revivedPlayer = Bukkit.getServer().getOfflinePlayer(revivedPlayerName);
					player.sendMessage(revivedPlayer.getName() + " / " + revivedPlayer.getName());
					getData().set(revivedPlayer.getName() + ".Death-Reason", null);
					getData().set(revivedPlayer.getName() + ".Death-Banned", null);
					getData().set(revivedPlayer.getName() + ".Time-Banned", null);
					getData().set(revivedPlayer.getName() + ".Revived", true);
					getData().set(revivedPlayer.getName() + ".Hearts", num);
					saveData();
					
					player.closeInventory();
					return;
				}
			}

			if (event.getSlot() == 21) {
				int num = getPlayerScore(player);
				if(num != 0) {
					setPlayerScore(player, num - 1);
				} else {
					return;
				}
			}

			if (event.getSlot() == 23) {
				int totalHearts = getData().getInt(player.getName() + ".Hearts-Deposited");
				int num = getPlayerScore(player);
				if(num < totalHearts && num < 20) {
					setPlayerScore(player, num + 1);
				}
			}
			Inventory inv = player.getOpenInventory().getTopInventory();
		    updateInventoryItems(inv, player);
		    player.updateInventory();
		}
	}
	
	@EventHandler
	public void onPlayerJoin(PlayerJoinEvent event) {
		Player player = (Player) event.getPlayer();
		if(getData().contains(player.getName().toString())) {
			if(getData().getBoolean(player.getName() + ".Revived") == true) {
				int newHearts = getData().getInt(player.getName() + ".Hearts");
				player.setMaxHealth(newHearts * 2);
				Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "spawn " + player.getName());
				getData().set(player.getName()  + ".Revived", null);
				getData().set(player.getName()  + ".Hearts", null);
				saveData();
			}
		}
	}
	
	public void updateInventoryItems(Inventory inv, Player player) {
		ItemStack heartCount = new ItemStack(Material.PAPER);
		ItemMeta heartCountMeta = heartCount.getItemMeta();
		heartCountMeta.setDisplayName("Use " + getPlayerScore(player) + " heart(s) to revive this player!");
		heartCountMeta.setCustomModelData(Integer.valueOf(10012));
		heartCountMeta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
		if (getPlayerScore(player) == 0) {
			ItemStack zeroHearts = new ItemStack(Material.BEDROCK);
			ItemMeta zeroHeartsMeta = heartCount.getItemMeta();
			zeroHeartsMeta.setDisplayName(ChatColor.AQUA + "Add Hearts!");
			zeroHearts.setItemMeta(zeroHeartsMeta);
			inv.setItem(13, zeroHearts);
		} else {
			heartCount.setAmount(getPlayerScore(player));
			heartCount.setItemMeta(heartCountMeta);
		    inv.setItem(13, heartCount); // Assuming 13 is the slot of the heart count item
		}
	}

	public int countCustomPaperItems(Player player) {
		int count = 0;
		for (ItemStack item : player.getInventory().getContents()) {
			if (item != null && item.getType() == Material.PAPER) {
				ItemMeta meta = item.getItemMeta();
				if (meta != null && meta.hasCustomModelData() && meta.getCustomModelData() == 10012) {
					count += item.getAmount();
				}
			}
		}
		return count;
	}
	
	@EventHandler
	public void onInventoryClose(InventoryCloseEvent event) {
		Player player = (Player) event.getPlayer();
		if(playerScores.containsKey(player)) {
			playerScores.remove(player);
		}
	}

	@EventHandler
	public void onInventoryClick(InventoryClickEvent event) {
		Player player = (Player) event.getWhoClicked();
		if (event.getView().getTitle().startsWith("Revive Station")) {
			event.setCancelled(true);

			if (event.getSlot() == 10) {
				openDeathBansInventory(player, 1);
			}

			if (event.getSlot() == 14) {
				double hearts = getData().getInt(player.getName() + ".Hearts-Deposited");
				if (hearts != 0) {
					getData().set(player.getName() + ".Hearts-Deposited", hearts - 1);
					saveData();
					double currentMaxHealth = player.getMaxHealth();
					if (currentMaxHealth == 40) {
						Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
								"iagive " + player.getName() + " custom_texture_items:heart 1 silent");
					} else {
						player.setMaxHealth(currentMaxHealth + 2);
					}
					ReviveStationInventory(player);
				}
			}

			if (event.getSlot() == 16) {
				ItemStack[] items = event.getWhoClicked().getInventory().getContents();
				int count = 0;

				for (ItemStack item : items) {
					if (item != null && item.getType() == Material.PAPER && item.hasItemMeta()
							&& item.getItemMeta().hasCustomModelData()
							&& item.getItemMeta().getCustomModelData() == 10012) {
						count++;
					}
				}

				if (count > 0) {
					double hearts = getData().getInt(event.getWhoClicked().getName() + ".Hearts-Deposited");

					if (event.isShiftClick()) {
						// Remove all items and update hearts for all items
						for (ItemStack item : items) {
							if (item != null && item.getType() == Material.PAPER && item.hasItemMeta()
									&& item.getItemMeta().hasCustomModelData()
									&& item.getItemMeta().getCustomModelData() == 10012) {
								int amount = item.getAmount();
								item.setAmount(0); // Remove the item
								hearts += 1.0D * amount;
							}
						}
					} else {
						// Remove only one item and update hearts for one item
						for (ItemStack item : items) {
							if (item != null && item.getType() == Material.PAPER && item.hasItemMeta()
									&& item.getItemMeta().hasCustomModelData()
									&& item.getItemMeta().getCustomModelData() == 10012) {
								if (item.getAmount() > 1) {
									item.setAmount(item.getAmount() - 1);
								} else {
									item.setAmount(0); // Remove the item
								}
								hearts += 1.0D;
								break;
							}
						}
					}
					getData().set(event.getWhoClicked().getName() + ".Hearts-Deposited", hearts);
					saveData();
					ReviveStationInventory(player);
				}
			}
		}
	}
	
	@EventHandler
	public void OpenReviveMenuFromBlock(PlayerInteractEvent event) {
	    Player player = event.getPlayer();
	    Action action = event.getAction();

	    // Check if the action is either right-click or left-click on a block
	    if(action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK) {
	        Block clickedBlock = event.getClickedBlock();
	        if (clickedBlock != null) {
	            // Get the location of the clicked block
	            Location loc = clickedBlock.getLocation();
	            
	            // Check if the block's location matches any of the specified coordinates
	            if((loc.getBlockX() == 19 && loc.getBlockY() == 66 && loc.getBlockZ() == -13) ||
	               (loc.getBlockX() == 19 && loc.getBlockY() == 65 && loc.getBlockZ() == -13) ||
	               (loc.getBlockX() == 19 && loc.getBlockY() == 64 && loc.getBlockZ() == -13)) {
	                
	                // Make the player execute the /ReviveStation command
	                player.performCommand("revivestation");
	            }
	        }
	    }
	}
	
	@EventHandler
	public void ClaimHeart(PlayerInteractEvent event) {
		Player player = (Player) event.getPlayer();
		if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
			if(player.getInventory().getItemInMainHand() != null) {
				ItemStack item = new ItemStack(player.getInventory().getItemInMainHand());
				if (item != null && item.getType() == Material.PAPER) { // Check if item is PAPER
		            ItemMeta meta = item.getItemMeta();
		            if (meta != null && meta.hasCustomModelData()) { // Check if item has custom model data
		                int modelData = meta.getCustomModelData();
		                if (modelData == 10012) { // Check if model data is 10012
		                	if(player.getMaxHealth() != 40.00) {
		                		double playerHP = player.getMaxHealth();
		                		player.setMaxHealth(playerHP + 2.00);
								int num = player.getInventory().getItemInMainHand().getAmount();
								player.getInventory().getItemInMainHand().setAmount(num -1);
								player.sendMessage(ChatColor.translateAlternateColorCodes('&', "&7&l(&4&l!&7&l) &3You successfully claimed 1 heart!"));
		                	} else {
								player.sendMessage(ChatColor.translateAlternateColorCodes('&', "&7&l(&4&l!&7&l) &3You're at max hearts already!"));
								event.setCancelled(false);
							}
		                }
		            }
		        }
			}
		}
	}
	

	Map<Player, List<KillRecord>> killRecords = new HashMap<>();
	private HashMap<Player, Integer> timer;

	@EventHandler
	public void onPlayerKillBoost(PlayerDeathEvent event) {
	    Player killer = event.getEntity().getKiller();
	    Player victim = event.getEntity();

	    if (killer == null || victim == null) return;

	    // Add this kill to the killer's record
	    KillRecord newRecord = new KillRecord(victim, System.currentTimeMillis());
	    killRecords.computeIfAbsent(killer, k -> new ArrayList<>()).add(newRecord);

	    // Check for kill boosting
	    checkForKillBoosting(killer);
	}

	public void checkForKillBoosting(Player killer) {
	    List<KillRecord> records = killRecords.get(killer);
	    if (records == null) return;

	    // Define your thresholds
	    int thresholdKills = 3;
	    long thresholdTime = 300000; // 5 minutes in milliseconds

	    // Filter and count recent kills of the same player
	    long currentTime = System.currentTimeMillis();
	    Map<Player, Long> killCount = records.stream()
	        .filter(record -> currentTime - record.getTime() < thresholdTime)
	        .collect(Collectors.groupingBy(KillRecord::getVictim, Collectors.counting()));

	    // Check if any count exceeds the threshold
	    killCount.forEach((victim, count) -> {
	        if (count >= thresholdKills) {
	            timer.put(killer, (20 * 60) * 30);
	            for(Player staff : Bukkit.getOnlinePlayers()) {
	            	if(staff.isOp()) {
	            		try {
	            			EmbedBuilder embedBuilder = new EmbedBuilder();
	            			embedBuilder.setTitle(String.valueOf(killer.getName()) + " has been accused of kill boosting");
	            			embedBuilder.setColor(Color.RED);
	            			MessageEmbed embed = embedBuilder.build();
	            			JDA jda = DiscordSRV.getPlugin().getJda();
	            			TextChannel channel = jda.getTextChannelById("1119752086939246612");
	            			if (channel != null) {
	            				channel.sendMessageEmbeds(embed, new MessageEmbed[0]).queue(
	            						success -> System.out.println("Embed sent successfully!"), error -> error.printStackTrace());
	            			} else {
	            				System.out.println("Channel not found!");
	            			}
	            		} catch (Exception e) {
	            			e.printStackTrace();
	            		}
	            	}
	            }
	        }
	    });
	}

	class KillRecord {
	    private final Player victim;
	    private final long time;

	    public KillRecord(Player victim, long time) {
	        this.victim = victim;
	        this.time = time;
	    }

	    public Player getVictim() {
	        return victim;
	    }

	    public long getTime() {
	        return time;
	    }
	}
}
Leave a Comment