Yeti

Name: rings smp Plugin: start off with a chiped ring. Every kill it levels up. 1 - 3 levels or 1-2 levels

Chain Chipped: Pull people towards you 25 block range. Offhand + crouch 45 second cooldown Normal: Pull towards things 50 block range. Right click + mainhand 1 minute cooldown Mastered: Wrap target around chain. Unable to move for 10 seconds. Punch player + mainhand 1.5 minute cooldown

Ring with tnt texture for model Tnt Chipped: Summon tnt and throw it at players. Crouch+ offhand 30 second cooldown DOESN’T DESTROY BLOCKS Normal: Throw 5 small tnts that latch on to the player. Rightclick + mainhand 1.5 minute cooldown DOESN’T DESTROY BLOCKS

Ring with redstone texture for model Redstone Chipped: Turn redstone into 3 shurakins and throw them at a player. Crouch + offhand 1 heart each 30 second cooldown Normal: Create a red circle particle shield around you. Right click + main hand 2 minute cooldown

please make a reroll for my plugin too.

Kodari AI
KodariWed at 11:07 pm 2
RingSMP
RingSMP is a Minecraft plugin featuring three upgradeable rings (Chain, TNT, Redstone) with chipped, normal, and mastered tiers. Each ring grants unique abilities triggered by crouch+offhand or right-click+mainhand, with cooldowns ranging from 30 seconds to 2 minutes. Rings level up per kill, starting from chipped. Chain rings pull entities, wrap targets, and immobilize; TNT rings throw explosive projectiles that never destroy blocks; Redstone rings throw shurikens or create particle shields. Includes a reroll system to randomize ring types and tiers, plus custom item models for each ring.
  • Give each player a random chipped ring, upgrade it through kills, and add a reroll command.

  • Implement each ring’s abilities and cooldowns, with TNT that leaves blocks intact.

Created Rings SMP with kill-based upgrades, ring abilities, and /ringreroll for operators.

Players receive a random chipped ring on first join. Rerolling resets it to chipped. The redstone shield blocks projectiles for 10 seconds, and ring TNT does not destroy blocks.

Yeti

Name: rings smp Plugin: start off with a chiped ring. Every kill it levels up. 1 - 3 levels or 1-2 levels

Chain Chipped: Pull people towards you 25 block range. Offhand + crouch 45 second cooldown Normal: Pull towards things 50 block range. Right click + mainhand 1 minute cooldown Mastered: Wrap target around chain. Unable to move for 10 seconds. Punch player + mainhand 1.5 minute cooldown

Ring with tnt texture for model Tnt Chipped: Summon tnt and throw it at players. Crouch+ offhand 30 second cooldown DOESN’T DESTROY BLOCKS Normal: Throw 5 small tnts that latch on to the player. Rightclick + mainhand 1.5 minute cooldown DOESN’T DESTROY BLOCKS

Ring with redstone texture for model Redstone Chipped: Turn redstone into 3 shurakins and throw them at a player. Crouch + offhand 1 heart each 30 second cooldown Normal: Create a red circle particle shield around you. Right click + main hand 2 minute cooldown

please make a reroll for my plugin too. can you also code the whole plugin for me

Kodari AI
KodariWed at 11:25 pm 2
  • Keep earlier abilities available as rings level up.

  • Make kill upgrades update the inventory slot reliably and space shuriken hits so each can deal damage.

The Rings SMP plugin is coded with all three ring types, kill-based upgrades, abilities, cooldowns, and /ringreroll for operators. I also made earlier abilities remain available after upgrading.

The rings currently use vanilla items, not custom ring models. To create the models, enable Kodari Studio under Project Settings → Generation, or for all projects at https://kodari.ai/settings?tab=features.

Yeti

can you make that when an op runs the command /ringstartup it tps everyone in a circle and then it shows gui on the screen that will loop through the different rings and then randomly select one.

Kodari AI
KodariWed at 11:32 pm 3
  • Add an operator-only /ringstartup command that gathers online players around the command runner.

  • Show each player a spinning ring-selection inventory, then replace their current ring with the randomly selected chipped ring.

Added /ringstartup for operators. It teleports online players into a circle around the command runner, then shows each player a spinning selection GUI and gives them a random chipped ring.

Running it replaces players’ current rings and resets their levels.

Yeti

can you make that when an op runs the command /ringstartup it tps everyone in a circle and then it shows gui on the screen that will loop through the different rings and then randomly select one. can you code this and make it so i can download it

Kodari AI
KodariWed at 11:34 pm 1

/ringstartup is already coded. Run it in-game as an operator to teleport online players into a circle and give each a randomly selected chipped ring through the spinning GUI.

To download the plugin:

  1. On desktop, click Compile in the top bar. On phone, tap ⋮ → Compile Project.

  2. Click Compile in the window.

  3. Once it succeeds, click Download on the build or the Download .jar button in chat.

Yeti

i don't see it

Kodari AI
KodariWed at 11:35 pm 1

Are you looking for the download button, or does /ringstartup not appear in-game?

The command is in the project. For the JAR, click Compile in the top bar (on phone: ⋮ → Compile Project), then click Compile in the window. The Download button appears after a successful build.

Yeti

the download for the .jar to download the /ringstartup button is not in the compile window.

Kodari AI
KodariWed at 11:38 pm 1

The Download button appears only after the build succeeds. In the Compile window, click Compile first, then look for Download on the completed build or Download RingsSMP.jar in the chat.

If the build fails instead, click Fix in the build window or Auto-fix in the chat. /ringstartup is included in the plugin JAR; it doesn’t have a separate download.

Yeti

Name: rings smp Plugin: start off with a chiped ring. Every kill it levels up. 1 - 3 levels or 1-2 levels

Chain Chipped: Pull people towards you 25 block range. Offhand + crouch 45 second cooldown Normal: Pull towards things 50 block range. Right click + mainhand 1 minute cooldown Mastered: Wrap target around chain. Unable to move for 10 seconds. Punch player + mainhand 1.5 minute cooldown

Ring with tnt texture for model Tnt Chipped: Summon tnt and throw it at players. Crouch+ offhand 30 second cooldown DOESN’T DESTROY BLOCKS Normal: Throw 5 small tnts that latch on to the player. Rightclick + mainhand 1.5 minute cooldown DOESN’T DESTROY BLOCKS

Ring with redstone texture for model Redstone Chipped: Turn redstone into 3 shurakins and throw them at a player. Crouch + offhand 1 heart each 30 second cooldown Normal: Create a red circle particle shield around you. Right click + main hand 2 minute cooldown

can you please code this. make sure that the activation for the powers work. add a command /rerollgive that will give the player a reroll. also add a /ringsmpstart that will give everyone a random chiped ring. make all the items non placeable. pretty much just create whole new items. the redstone dust texture is just gonna be a redstone dust.

Kodari AI
KodariThu at 12:22 am 6
  • Add /rerollgive tokens and /ringsmpstart, while keeping the existing startup command.

  • Protect custom items from placement and make ability activation explicit and reliable.

  • Use the supplied ring images where the project can support them; redstone stays as redstone dust.

Updated Rings SMP with the ring abilities, kill upgrades, cooldowns, and non-placeable ring items.

  • /rerollgive [player] gives a right-click reroll token.

  • /ringsmpstart gives every online player a random chipped ring, replacing their current ring.

  • For chipped abilities, hold the ring in your offhand, crouch, and press F. Normal abilities use right-click in the main hand.

The supplied chain and TNT images aren’t applied yet: custom item textures require a resource pack. Redstone uses vanilla redstone dust.

To get the JAR, open Compile, click Compile, then download the successful build.

Yeti

The tnt should do more damage. The mastered tnt power makes all of the tnt latch onto the person. it should shoot like the first power and spread out a bit. only one tnt should latch onto the player. the redstone shield power doesn't make the player invincible. the when you use the chain powers and try to pull toward something it doesn't bring you the full way. there should also be a chain that follows where the chain was lunched.

Kodari AI
KodariThu at 12:54 am 3
  1. Increase TNT damage and spread the multi-TNT throw, with at most one TNT attaching.

  2. Make the redstone shield grant invincibility.

  3. Extend the chain pull to its target and show the chain along its path.

Updated the abilities:

  • TNT: Increased explosion damage. The five-TNT ability now throws a spread, with only the center TNT able to latch onto a player. Ring TNT still doesn’t destroy blocks.

  • Redstone: The shield now blocks all damage for its 10-second duration.

  • Chain: Pulling continues toward the target rather than relying on one velocity boost. A gray particle chain shows the connection during the pull.

The five-TNT ability is currently the Normal TNT ability; TNT rings have two levels.

Yeti

make the reroll force your ring to go in your offhand and swap between the different rings in your offhand, this should be around 5 seconds long. every time it swaps there should be a (tick) sound becoming higher pitched every time it swaps. and once it finally finishes it makes a (ding) sound. make the text say "Your ring swaped from (the current ring they have) to the (ring that they get)" make sure you cannot get the same ring twice.

Kodari AI
KodariThu at 4:30 pm 7
  • Animate rerolls in the offhand for five seconds, with rising ticks and a final ding.

  • Preserve the displaced offhand item and guarantee a different ring.

Rerolls now cycle rings in your offhand for five seconds, with rising tick sounds and a final ding. The result is always a different ring, and your previous offhand item is preserved.

Yeti

i think that if you change the tnt activations it will work better. make the chipped tnt power activate offhand + right click (this makes it so that you can throw tnt while holding out a sword) also make the tnt for the first power blow up when it hits the ground or a player. the the second power make the activation crouch + offhand.

Kodari AI
KodariThu at 4:37 pm 2
  • Move the chipped TNT throw to offhand + right-click and detonate it on impact.

  • Move the five-TNT ability to crouch + offhand swap, keeping its existing cooldown and level requirement.

Updated the TNT abilities:

  • Chipped: Hold the ring in your offhand and right-click, including while holding a sword. The TNT explodes when it hits the ground or another player.

  • Normal: Hold the ring in your offhand, crouch, and press F to launch the five-TNT spread.

The cooldowns remain unchanged, and ring TNT still won’t destroy blocks.

Yeti

Make it so that theres little icons above your hot bar. the chipped power can be a broken heart. on the right side add the cooldown for the chipped power. for the normal power make it lightning bolt. also add the cooldown on the right side. for the mastered power make it a ring. (do this for all rings) (the rings don't all have mastered powers.) (if a ring is chipped only show the chiped icon) (if the ring is normal show the chipped and normal icon) (if the ring is mastered show the chipped, normal, and mastered icons.)

Kodari AI
KodariThu at 4:44 pm 2
  • Show each unlocked power and its remaining cooldown above the hotbar.

  • Update the display as the ring levels up or its cooldowns change.

Added an action-bar display above the hotbar showing each unlocked power and its cooldown:

  • 💔 Chipped

  • ⚡ Normal

  • 💍 Mastered, for the chain ring

Each icon shows Ready or the seconds remaining. The display updates as the ring levels up.

Yeti

make it so you can use the chipped tnt power even if you don't have a sword out. it just needs to be offhanded and you have to rightclick

Kodari AI
KodariThu at 4:48 pm 1

I’ll handle right-clicks from either hand while keeping the TNT ring in the offhand, and prevent one click from triggering twice.

Updated chipped TNT to activate on right-click with the ring in your offhand, regardless of what’s in your main hand.

Yeti

make it so when i run the command /ringstartup a big particle explosion happens where i'm standing everyone tps in a circle around me. a white particle circle starts slowing levating into the sky it stops and starts to hover and shoots different colored beams at the players. the players can't move and are forced to look forward, a bit up but forced to keep looking in the middle of the circle. all the rings float in front of the players changing slowing making a (tick sound) getting higher pitched. it picks a random ring for the players. another explosion happens and all the particles fade away.

Kodari AI
KodariThu at 5:06 pm 7

I’ll replace the startup GUI with a shared particle ceremony, lock participants’ positions and view during it, and show each player a floating ring selection before awarding the result.

Updated /ringstartup with a shared ceremony: an opening explosion, a rising white particle circle, colored beams, and floating rings that cycle with rising tick sounds before each player receives a random chipped ring.

Players are held in place facing the center until the final explosion. The ceremony replaces the previous selection GUI.

Yeti

make the particle circle a sphere the beam covers up the rings making the rings not possible to see.

Kodari AI
KodariThu at 5:09 pm 3

I’ll make the rising shape a sphere and keep beam particles out of the players’ view of their rings.

Changed the rising particle circle into a sphere and kept beam particles clear of players’ view of the floating rings.

Yeti

make it so that after i run the command /ringstartup and everything for the start ends. a text on the screen pops up that says "Grace" in green letters. make the grace last 15 minutes. there should be a text that shows how long it is until grace ends. you can choose where to put the text. during grace period pvp is disabled. once the 15 minutes end add a text that says "PVP ON" and pvp enables. can you also make it so that if you die your ring doesn't drop?

Kodari AI
KodariThu at 5:22 pm 4
  1. Start a 15-minute PvP grace period after the startup ceremony, with a visible timer and end announcement.

  2. Keep rings on death.

Added a 15-minute grace period after /ringstartup finishes. A green Grace title appears, and a boss bar shows the remaining time. PvP is disabled until the timer ends, when PVP ON appears.

Rings no longer drop on death; they’re returned on respawn.

Yeti

add a ender dragon roar when the titles apear

Kodari AI
KodariThu at 5:23 pm 1

Added an Ender Dragon roar when the Grace and PVP ON titles appear.

Yeti

i made 2 new powers. please add them to the plugin. Popped chorus fruit Chipped: teleport wherever you are looking. 25 block range offhand+ any item rightclick. 45 second cooldown normal: teleport around 5 times then teleport behind the player. Crouch + offhand 1.5 minute cooldown

Music Disk Chipped: Command /Musicdiskfind shows a gui. With every player online, you press the player and insert a noteblock or juke block. It will create a large particle beam pointing towards the player. Once the player is in a 100 block distance of the player they selected the beam disappears. It shows a text on both of the players screens “a player is nearby…” make sure the text is red. Command /Musicdiskfind shows a gui. 30 minute cooldown Normal: become FULL invis play walking sounds behind the player. (LOUD) then un invis and teleport behind the player Crouch + offhand 1.5 minute cooldown

Kodari AI
KodariThu at 6:09 pm 9
  • Add both rings to random selection, rerolls, upgrades, and the cooldown display.

  • Add chorus teleports and the music-disc tracking GUI and stealth ability.

Added the chorus fruit and music disc rings to starting selections, rerolls, and kill-based upgrades.

  • Chorus: Right-click with the ring in your offhand to teleport where you’re looking. At normal level, look at a player within 25 blocks, crouch, and press F to teleport around them, then behind them.

  • Music disc: Use /musicdiskfind, place a note block or jukebox in the payment slot, and select a player. At normal level, look at a player within 25 blocks, crouch, and press F for the invisibility ambush.

Both rings show their unlocked abilities and cooldowns above the hotbar.

Yeti

Crossbow NO ARROWS NEEDED chipped: everytime you shoot an arrow it will have a random effect. (jump boost 2 11 seconds 50% chance) (slowness 3 11 second 30% chance) (weakness 3 seconds 20% chance) Normal: every time you shoot and hit a player there is a 30% chance that the crossbow will be fully charged again.

Mastered: a large cross bow appears in front of the player who used it. It reels back and then the player who used it has to aim at the player and it shoots 30 arrows like a minigun at the player they wanna kill. Crouch + offhand Arachnid ring (cobweb for the model) Chipped: Hit a player and they become webbed/stunned for 5 seconds.(hit player + must be holding the ring) normal: throw cobwebs at a player (make sure that the cobwebs do not destroy blocks they only get placed) (5 block radius circle) 1.5 minute. Mainhand + rightclick

Snowball ring (Snowball) Chipped: Throw a snowball at a player. If it hits, they receive Slowness III for 4 seconds. Right-click + mainhand 1 minute cooldown Normal: Throw an ice block at a player that splits into 5 separate ice icicles that lunch to the player. 3 of the icicles act like homing missiles that chase the player.

here are a few new rings. if you see any imperfections please tell me. fix everything. add a command that works like /ringsmpgive [username] [any ring] this command will give any player any ring. add another command /ringsmpbordersize [anynumber] [anynumber] this command will change the world border. make sure that when you die and respawn your ring doesn't dupe. make a recipe to craft the rerolls. The recipe will be 4 diamond blocks in the corners, one ender pearl in the middle, and four gold blocks to fill in the rest. whenever you die your ring should downgrade by one stage. mastered to normal - chipped. Also the tnt blows up armor stands which can mess up traps, fix that please. you can also teleport to armorstands with chorus and other stuff please fix that. simply make mobs not count for the powers unless its a arrow type of thing. make sure that if the player is being suffacated or if there are any banners n' stuff they can't use their powers. make the tnt for the normal power not do as much damage, because it shoots 5 it can be really strong. add a /ringsmpgrace [start] or [End] if you do start it starts grace with out the server start up, just the text says, if you end it, it ends the grace period early. also add a /upgradering command that will upgrade the ring you are holding in your main hand. (chipped to normal) (normal to mastered)

Kodari AI
KodariFri at 12:03 am 5

I’ll add the three rings and admin commands, then address death handling, targeting, TNT damage, grace control, and the reroll recipe. A few ability details aren’t specified, so I’ll use sensible defaults and list them afterward.

Added the crossbow, arachnid, and snowball rings, plus the requested commands, reroll recipe, death downgrade, targeting protections, and TNT adjustments.

Admin commands: /ringsmpgive <player> <ring>, /ringsmpbordersize <size> <seconds>, /ringsmpgrace <start|end>, and /upgradering.

Defaults for unspecified details: the crossbow barrage and ice ability have 90-second cooldowns; the arachnid webs disappear after 10 seconds. Use sneak + main-hand right-click for the ice ability.

The barrage uses a floating crossbow item, not a large custom model. The changes still need an in-game test; I haven’t verified the abilities on a server.

Yeti

The cross bow shoots way to fast just in its normal form. the mastered power should not shoot that fast, make all the 30 arrows take 5 seconds to shoot, make the crossbow not levatate it should hover infront of the player. make it follow the direction of where the player is looking. make the mastered power a normal power instead. the normal power for the crossbow should have a 2 minute cooldown. add a new command. /recipes, it should show all the recipes that you can make and how to make them. add 2 new recipes, keep the reroll one to. 1. Easy Gaps, normal gap recipe but get rid of the gold in the corners. 2. easy anvils, get rid of two iron blocks on the right bottom and left bottom sides, (keep the one in the middle bottom) replace the ones on the right and left with iron ingots.

Kodari AI
KodariFri at 12:29 am 8
  1. Slow the crossbow and move its barrage to the normal power.

  2. Add the two recipes and a /recipes guide, keeping the reroll recipe.

Updated the crossbow and recipes:

  • The crossbow takes time to load. Its barrage is now the normal power, with a two-minute cooldown; it fires 30 arrows over five seconds while following your aim.

  • /recipes shows the reroll, easy golden apple, and easy anvil recipes.

  • For the anvil, I interpreted your description as replacing the left and right iron blocks in the top row with ingots, leaving the center block.

The crossbow’s previous chance-to-reload normal power was replaced by the barrage.

Yeti

Ok, you removed all of the commands can you please fix that and get rid of the recipes command too. and i have a new idea for the chipped power and normal power for snowball.

Snowball:

Chipped: throw a snowball at a player to freeze/stun the player for 3 seconds and give them slowness 3 for 3 seconds after. 1 minute cooldown Normal: Shoot 5 icicles at a player dealing 1 heart each. 1.5 minute cooldown. crouch + offhand activation The crossbow also has a few updates for itself too.

Crossbow NO ARROWS NEEDED (make sure the bow shoots at normal speeds at first) Passives: everytime you shoot an arrow it will have a random effect. (jump boost 2 11 seconds 50% chance) (slowness 3 11 second 30% chance) (weakness 3 seconds 20% chance) Every time you shoot and hit a player there is a 30% chance that the crossbow will be fully charged again.

Chipped: Quickcharge 7 on crossbow for 5 seconds. Mainhand+ left click. (must be holding out crossbow) 45 second cooldown normal: a large cross bow appears in front of the player who used it. It reels back and then the player who used it has to aim at the player and it shoots 30 arrows like a minigun at the player they wanna kill. Crouch + offhand 2.5 minute cooldown.

When someone uses the normal power it the crossbow should look as if you are holding it in your main hand. but it should also float. When someone aims make sure it isn't laggy, it should only turn left and right. but the arrows should still shoot up and down too. make the normal power take 5 seconds to use in total. just so it is not as op.

Make it so that you can use your normal power to latch onto players and get pulled towards the player you used your normal power on

Make sure that all of the rings can’t break.

Add one new command.

/Ringsmp:event [INVIS] [ANARCHY]

When you pick invis it will make all players invis for 1.5 hours. Do not put a timer anywhere.

When you pick Anarchy it will have a timer, somewhere you get to pick.

Make the rings look enchanted so it looks better please.

Kodari AI
KodariToday at 12:15 am 7
  1. Restore the plugin commands and remove /recipes.

  2. Rework snowball, crossbow, and chain abilities.

  3. Make rings unbreakable and enchanted-looking.

  4. Add the invisibility and anarchy events.

Updated the snowball, crossbow, and chain powers, made rings unbreakable with an enchanted glow, and removed /recipes while keeping the crafting recipes. The existing commands remain registered.

  • /ringsmp:event invis starts 90 minutes of invisibility without a boss-bar timer. Standard invisibility still leaves armor and held items visible.

  • /ringsmp:event anarchy [minutes] starts a boss-bar timer; it defaults to 90 minutes.

What gameplay rules should the Anarchy event change? For now, it only announces the event and shows its timer. The changes still need an in-game test.

Kodari can make mistakes. Review important code before using.
Files
src
Code
2 1,744
src/main/java/com/kodari/ringssmp/RingsSMP.java
package com.kodari.ringssmp;

import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XEnchantment;
import com.cryptomorin.xseries.XItemFlag;
import com.cryptomorin.xseries.particles.XParticle;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.Particle;
import org.bukkit.World;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.AbstractArrow;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Snowball;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.entity.ItemMergeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryPickupItemEvent;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.CrossbowMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import com.cryptomorin.xseries.XPotion;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public final class RingsSMP extends JavaPlugin implements Listener {
    private NamespacedKey ringKey;
    private NamespacedKey levelKey;
    private NamespacedKey explosiveKey;
    private NamespacedKey initializedKey;
    private NamespacedKey rerollKey;
    private final Map<String, Long> cooldowns = new HashMap<>();
    private final Map<UUID, Long> rooted = new HashMap<>();
    private final Map<UUID, Long> shields = new HashMap<>();
    private final Map<UUID, Inventory> startupInventories = new HashMap<>();
    private final Map<UUID, String> startupSelections = new HashMap<>();
    private final Map<UUID, Location> startupPositions = new HashMap<>();
    private final Map<UUID, Item> startupDisplays = new HashMap<>();
    private boolean startupRunning;
    private final Map<UUID, String[]> rerolls = new HashMap<>();
    private final Set<UUID> tntClicks = new HashSet<>();
    private final Set<UUID> crossbowLoading = new HashSet<>();
    private final Map<UUID, Long> quickCharge = new HashMap<>();
    private final Set<Entity> barrageDisplays = new HashSet<>();
    private final Map<UUID, List<ItemStack>> retainedRings = new HashMap<>();
    private long graceEnds;
    private BossBar graceBar;
    private BossBar anarchyBar;
    private long invisEnds;
    private long anarchyEnds;
    private static final String[] RING_TYPES = {"chain", "tnt", "redstone", "chorus", "music", "crossbow", "arachnid", "snowball"};
    private final Map<UUID, Inventory> musicMenus = new HashMap<>();
    private final Map<UUID, Inventory> recipeMenus = new HashMap<>();
    private final Map<UUID, Map<Integer, UUID>> musicMenuTargets = new HashMap<>();
    private final Set<UUID> hiddenPlayers = new HashSet<>();
    private final Set<UUID> trackingPlayers = new HashSet<>();

    @Override
    public void onEnable() {
        ringKey = new NamespacedKey(this, "ring");
        levelKey = new NamespacedKey(this, "level");
        explosiveKey = new NamespacedKey(this, "ring_explosive");
        initializedKey = new NamespacedKey(this, "initialized");
        rerollKey = new NamespacedKey(this, "reroll_token");
        graceEnds = getConfig().getLong("grace-ends", 0L);
        invisEnds = getConfig().getLong("invis-event-ends", 0L);
        anarchyEnds = getConfig().getLong("anarchy-event-ends", 0L);
        graceBar = Bukkit.createBossBar("Grace", BarColor.GREEN, BarStyle.SOLID);
        anarchyBar = Bukkit.createBossBar("Anarchy", BarColor.RED, BarStyle.SOLID);
        Bukkit.getPluginManager().registerEvents(this, this);
        ShapedRecipe recipe = new ShapedRecipe(new NamespacedKey(this, "reroll_recipe"), createReroll());
        recipe.shape("DGD", "GEG", "DGD");
        recipe.setIngredient('D', XMaterial.matchXMaterial("DIAMOND_BLOCK").get().parseMaterial());
        recipe.setIngredient('G', XMaterial.matchXMaterial("GOLD_BLOCK").get().parseMaterial());
        recipe.setIngredient('E', XMaterial.matchXMaterial("ENDER_PEARL").get().parseMaterial());
        Bukkit.removeRecipe(new NamespacedKey(this, "reroll_recipe"));
        Bukkit.addRecipe(recipe);
        ShapedRecipe gap = new ShapedRecipe(new NamespacedKey(this, "easy_gap"), XMaterial.matchXMaterial("GOLDEN_APPLE").map(XMaterial::parseItem).orElseThrow(IllegalStateException::new));
        gap.shape(" G ", "GAG", " G ");
        gap.setIngredient('G', XMaterial.matchXMaterial("GOLD_INGOT").get().parseMaterial());
        gap.setIngredient('A', XMaterial.matchXMaterial("APPLE").get().parseMaterial());
        Bukkit.removeRecipe(new NamespacedKey(this, "easy_gap"));
        Bukkit.addRecipe(gap);
        ShapedRecipe anvil = new ShapedRecipe(new NamespacedKey(this, "easy_anvil"), XMaterial.matchXMaterial("ANVIL").map(XMaterial::parseItem).orElseThrow(IllegalStateException::new));
        anvil.shape("IBI", " I ", "III");
        anvil.setIngredient('I', XMaterial.matchXMaterial("IRON_INGOT").get().parseMaterial());
        anvil.setIngredient('B', XMaterial.matchXMaterial("IRON_BLOCK").get().parseMaterial());
        Bukkit.removeRecipe(new NamespacedKey(this, "easy_anvil"));
        Bukkit.addRecipe(anvil);
        Bukkit.getScheduler().runTaskTimer(this, this::renderShields, 0L, 5L);
        Bukkit.getScheduler().runTaskTimer(this, this::renderCooldowns, 0L, 5L);
        Bukkit.getScheduler().runTaskTimer(this, this::updateGrace, 0L, 20L);
        Bukkit.getScheduler().runTaskTimer(this, this::updateEvents, 0L, 20L);
    }

    @Override
    public void onDisable() {
        for (Player player : Bukkit.getOnlinePlayers()) finishSelection(player);
        startupDisplays.values().forEach(Entity::remove);
        startupDisplays.clear();
        barrageDisplays.forEach(Entity::remove);
        barrageDisplays.clear();
        for (Player player : Bukkit.getOnlinePlayers()) finishReroll(player);
        for (UUID id : new HashSet<>(hiddenPlayers)) revealPlayer(id);
        graceBar.removeAll();
        anarchyBar.removeAll();
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        for (UUID id : hiddenPlayers) {
            Player hidden = Bukkit.getPlayer(id);
            if (hidden != null) player.hidePlayer(this, hidden);
        }
        if (!player.getPersistentDataContainer().has(initializedKey, PersistentDataType.BYTE)) {
            player.getPersistentDataContainer().set(initializedKey, PersistentDataType.BYTE, (byte) 1);
            give(player, createRing(randomType(), 1));
            player.sendMessage(ChatColor.GOLD + "You received your first chipped ring!");
        }
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (command.getName().equalsIgnoreCase("ringevent")) {
            if (!sender.hasPermission("ringssmp.admin")) { sender.sendMessage(ChatColor.RED + "No permission."); return true; }
            if (args.length == 1 && args[0].equalsIgnoreCase("invis")) {
                invisEnds = System.currentTimeMillis() + 90 * 60 * 1000L;
                getConfig().set("invis-event-ends", invisEnds);
                saveConfig();
                updateEvents();
                Bukkit.broadcastMessage(ChatColor.LIGHT_PURPLE + "The invisibility event has started!");
                return true;
            }
            if ((args.length == 1 || args.length == 2) && args[0].equalsIgnoreCase("anarchy")) {
                try {
                    int minutes = args.length == 2 ? Integer.parseInt(args[1]) : 90;
                    if (minutes < 1 || minutes > 10080) throw new IllegalArgumentException();
                    anarchyEnds = System.currentTimeMillis() + minutes * 60000L;
                    getConfig().set("anarchy-event-ends", anarchyEnds);
                    saveConfig();
                    updateEvents();
                    Bukkit.broadcastMessage(ChatColor.RED + "The anarchy event has started!");
                } catch (IllegalArgumentException ex) { sender.sendMessage(ChatColor.RED + "Use a duration from 1 to 10080 minutes."); }
                return true;
            }
            sender.sendMessage(ChatColor.RED + "Usage: /ringsmp:event <invis|anarchy> [anarchy minutes]");