S

Name Of The Plugin APracticeCore, Author Nya AnunglT, Package nya AnunglT.Apracticecore, dan ip nya itu cookiessmp.my.id

📎 1 file 8,776 chars
📄
pasted-code-1792694511672.txt
txt 89 lines
▶
# ROLE
You are a senior Minecraft plugin engineer. This is PHASE 1 of 5 of a plugin named "VDuels" that recreates the GUI-driven lobby experience of the "Vanilla Practice" server (vanillapractice.com). Reproduce every menu title, item, tooltip line, color, click behavior and chat message below with maximum fidelity. Do not rename, simplify or "improve" the UX. Build the foundation so later phases (Queue, Party, Kit Editor, Match Flow) plug in without refactoring.

# TECH STACK
- Java 21, Paper API 1.21.x, Folia-compatible (scheduler abstraction using global/region/entity/async schedulers; never raw Bukkit.getScheduler on Folia paths).
- Gradle (Kotlin DSL). Adventure + MiniMessage for all text. No NMS unless unavoidable.
- Storage: SQLite default, optional MySQL (HikariCP). All DB I/O async. Per-player data cached in memory, saved on quit and every 5 minutes.
- Config files: config.yml, messages.yml, guis/settings.yml, guis/privacy.yml, guis/display.yml, guis/account.yml. Every GUI fully configurable (title, slots, material, name, lore, sounds). /vduels reload hot-reloads everything.
- Permission prefix: vduels.*

# PACKAGE STRUCTURE
core (plugin main, scheduler abstraction), storage (SQLite/MySQL, PlayerData cache), gui (GuiManager, BaseGui, GuiItem, click handling), settings (PlayerSettings model + the 3 setting GUIs), lobby (hotbar, scoreboard, actionbar, spawn, protection), message (MessageService), util, listener, command.
Design the GUI framework generically: BaseGui with title, rows, slot->GuiItem map, per-item click handlers (left/right/shift), in-place item refresh, back-navigation stack, onClose hooks. Phases 2-4 will reuse it.

# GLOBAL UI CONVENTIONS (apply to every GUI)
- All clicks, drags, shift-clicks, number-key swaps, double-clicks and offhand swaps are cancelled in plugin GUIs. Items are non-movable.
- Tooltip format: line 1 = colored title; then 1-2 gray description lines; blank line; optional "Status: "; blank line; action line.
- Action line: the word "Click" in yellow + underlined, the rest white. Examples: "Click to toggle.", "Click to open.", "Click to cycle Everyone / Friends / None."
- Status colors: On = green, Off = red, Everyone = green, Friends = yellow, None = red, Online = green, Do Not Disturb = yellow/gold.
- Submenu titles start with a small colored back-arrow glyph then the name: "< Settings" style, e.g. "< Privacy", "< Display", "< Account". Privacy/Display titles cyan, Account title green.
- Back button: red "Back" with gray description "Return to settings." Placed in the lower-left area of submenus. Clicking returns to the Settings GUI.
- Decorative filler panes are named "Filler" with description "Decorative — players cannot interact".
- Every click plays a soft UI sound (configurable). Toggles play higher pitch for On, lower for Off.
- Toggle clicks update the item in place (no GUI reopen/flicker) and send a chat confirmation.

# LOBBY EXPERIENCE
Scoreboard (right side), flicker-free (per-player, update only changed lines):
  Title: "Vanilla Practice" (cyan), subline shows region + live ping, e.g. "AS | 20".
  Header "Server" (cyan), then lines with icons:
    ☆ Level:       ✔ Online:  (green)      ● Coins:  (gold)      ⚔ Kills:  (red)
  Footer: VANILLAPRACTICE.COM (gray)
Animated actionbar (branding/tips cycle, configurable frames).
Both are toggleable per player (Display menu) and persist.
Lobby hotbar (fixed items; cannot be moved, dropped or swapped; slot indexes configurable). Item names appear in the actionbar when selected:
  - Queue: name "Queue", lore "Duel Menu" / "Click to browse queues." (opens Queue GUI in Phase 2; for now send a placeholder message)
  - Party: name "+ Party", lore "Duel Menu" / "Click to create a party." (Phase 2 placeholder)
  - Kit Editor: book item, actionbar text "Kit Editor" (Phase 4 placeholder)
  - Settings: lime/green item, actionbar text "Settings" -> opens Settings GUI
Lobby is a safe zone: no damage, no hunger, no item drop/pickup, no block break/place, no inventory moving, fixed spawn. Spawn Preference (New/Old spawn, see Account) is applied on join and respawn. Spawn locations are set with /vduels setspawn .

# SETTINGS GUI (3 rows)
Title "Settings". Three entries:
  1. Privacy (book and quill): "Chat and request controls." / "Click to open."
  2. Display (item frame): "HUD, sounds, and chat noise." / "Click to open."
  3. Account (nether star): "Presence, spawn, friends, and extras." / "Click to open."
Opened by the lobby Settings item and by /settings.

## Privacy (title "< Privacy")
- Private Messages: click cycles Everyone -> Friends -> None. Title "Private Messages: " (value colored). Lore: "Who may send you private messages (/msg)." / "Status: " / "Click to cycle Everyone / Friends / None."
- TPA Requests: same cycle. Title "TPA Requests: ". Lore: "Who may send you teleport requests." / "Status: " / "Click to cycle Everyone / Friends / None."
- Player Visibility (eye-of-ender style item): toggles hiding other players in the lobby (use Player#hidePlayer/showPlayer). Chat: "Players hidden." / "Players are now visible." [VERIFY exact item name]
- Back button.
Chat feedback: "Friends » Private messages allowed from ." and "Friends » TPA requests are now allowed from ." ("Friends »" prefix green, value in its status color).
/msg and /tpa must actually enforce these settings (Everyone / only friends / nobody). Provide a simple friend-check interface (FriendProvider) with a stub implementation; the friends system itself can come later.

## Display (title "< Display")
Toggle items, each with name, description, "Status: On/Off", "Click to toggle.":
  - Actionbar Display — "Toggle the animated server actionbar."
  - Scoreboard — "Toggle your scoreboard display."
  - Announcement Sounds — "Toggle sounds for server announcements."
  - Join Messages — "Toggle seeing player join messages."
  - Leave Messages — "Toggle seeing player leave messages."
  - Back button.
Chat feedback: "Actionbar enabled." (green) / "Actionbar disabled." (red); "Scoreboard enabled." / "Scoreboard disabled."; "Join-Leave » Join messages: On/Off" (prefix gold). Join/leave messages must be filtered per viewer (suppress the vanilla broadcast and send manually to players who have it enabled).

## Account (title "< Account", green)
  - Presence: toggles Online <-> Do Not Disturb. Title "Presence: "; lore "Online or Do Not Disturb." / "Status: " / "Click to toggle." Do Not Disturb blocks duel invites, party invites, friend requests and TPA (expose PresenceService.isDnd(player) for later phases).
  - Spawn Preference: lore "Choose which spawn you prefer." / blank / "Current: " (white) / blank / "Left-click for New Spawn." / "Right-click for Old Spawn." (action words yellow underlined).
  - Fast Crystals: "Enable faster crystal placement." / "Status: On/Off" / "Click to toggle." Store the flag and expose it to Phase 4/5; implement basic server-side handling of end-crystal place/hit with strict packet-rate sanity checks.
  - Back button.

# PERSISTENCE
PlayerData table: uuid, name, level, xp, coins, kills, settings (privateMessages, tpaRequests, playersVisible, actionbar, scoreboard, announcementSounds, joinMessages, leaveMessages, presence, spawnPreference, fastCrystals). Defaults: messages Everyone, TPA Everyone, actionbar On, scoreboard On, announcement sounds On, join/leave On, presence Online, spawn New, fast crystals Off. Settings are loaded async on AsyncPlayerPreLogin and applied instantly on join.

# MESSAGES
All strings in messages.yml (MiniMessage). Prefixes: "Duels »" (cyan), "Friends »" (green), "Join-Leave »" (gold). Success green, errors red, values white/yellow. Keep strings identical to the ones above.

# PERFORMANCE & SAFETY
- No blocking I/O on main/region threads. Pre-parse and cache MiniMessage and GUI items. Update only changed slots/lines.
- Rate-limit GUI clicks; validate every click server-side; tag GUI items with PersistentDataContainer; close plugin GUIs on world change, teleport and quit.
- Clean up all per-player caches/scoreboards on quit (no memory leaks).

# DELIVERABLES
1. Full source for this phase with the package structure above.
2. Default config.yml, messages.yml and guis/*.yml.
3. Commands: /settings, /vduels reload, /vduels setspawn , plus enforcement hooks for /msg and /tpa.
4. Permissions list (vduels.*) and README section.
5. A test checklist verifying every tooltip, color, toggle and chat message in this spec.
Do not implement Queue, Party, Kit Editor or match logic yet; leave clean extension points and placeholders.
Kodari AI
KodariOct 22 at 6:49 pm 4
APracticeCore
APracticeCore is a Folia-compatible Paper plugin recreating the GUI-driven lobby experience of the Vanilla Practice server. It provides a fully configurable Settings menu system with Privacy, Display, and Account submenus, featuring toggleable private messages, TPA requests, player visibility, actionbar, scoreboard, announcement sounds, join/leave messages, presence status, spawn preference, and fast crystals. The plugin includes a persistent player data system with SQLite/MySQL storage, animated actionbar, flicker-free per-player scoreboard, protected lobby spawn with hotbar items, and a generic GUI framework with click handling, back-navigation, and in-place item refresh. All text uses Adventure MiniMessage with configurable messages and hot-reload support.
  1. Set up the APracticeCore Paper project and configuration files.

  2. Build player settings, async persistence, and the reusable GUI framework.

  3. Add settings menus, lobby protection/HUD, and the requested commands and request checks.

  4. Include a README with permissions and a Phase 1 verification checklist.

Created the APracticeCore project for cookiessmp.my.id with the requested package and author. It includes the configurable settings GUIs, SQLite/MySQL storage configuration, Folia scheduler helpers, lobby protections and HUD, spawn preferences, /settings and /vduels commands, and /msg//tpa enforcement hooks. The README includes permissions and a Phase 1 verification checklist.

S
📎 1 file 6,836 chars
📄
pasted-code-1792705677046.txt
txt 68 lines
▶
# ROLE
You are a senior Minecraft plugin engineer. This is PHASE 2 of 5 of the "VDuels" plugin (recreating the Vanilla Practice server experience, vanillapractice.com). Phase 1 (core, GuiManager/BaseGui, storage, scoreboard, hotbar, Settings GUIs, PresenceService) already exists. Reuse its framework, message service, scheduler abstraction and conventions. Do NOT rewrite Phase 1. Implement the Queue GUI and the matchmaking queue with maximum fidelity to the behavior below. Party and Kit Editor come later; leave clean hooks for them.

# TECH STACK (same as Phase 1)
Java 21, Paper 1.21.x, Folia-compatible (use the existing scheduler abstraction), Adventure/MiniMessage, async DB I/O, config-driven everything, /vduels reload supported.

# NEW PACKAGES
kit (Kit model, KitRegistry, KitRules), queue (QueueManager, QueueEntry, Matchmaker, QueueGui), stats (live active/queued counters). Put the Match hand-off behind an interface `MatchStarter` (Phase 5 implements it; for now provide a stub that logs and messages "Match found!").

# GLOBAL UI CONVENTIONS (unchanged)
- All clicks/drags/shift/number-key/offhand swaps cancelled; items non-movable.
- Tooltip: colored title, gray description, blank line, details, blank line, action line.
- Action line: the word "Click" yellow + underlined, rest white.
- Filler panes named "Filler" / "Decorative — players cannot interact".
- Soft click sound (configurable). In-place item updates, no reopen flicker.

# KIT MODEL (config-driven: kits.yml)
Each kit: id, display name, icon material, icon prefix glyph (small colored icon shown before the name), ranked (bool), enabled (bool), slot in the GUI, team sizes allowed, default layout (used until the player edits it in Phase 4), rules (hunger, natural regen, build/break allowed, crystals allowed, etc.).
Kits seen in the game (ship these as defaults; names must match exactly):
  Sword (diamond sword), Axe, Mace, Spear Mace, DiaPot (diamond-pot icon), SMP (grass block), Creeper (green creeper-style icon), Bed PvP (red bed), plus crystal / pot / netherite sword variants. [VERIFY exact full list and slot positions from the videos; make every slot configurable]

# QUEUE GUI
- Opened by the lobby "Queue" hotbar item ("Queue" / "Duel Menu" / "Click to browse queues.") and by /queue.
- 6 rows. Title "Select Kit" [VERIFY]. Blue stained-glass "Filler" border on the top row and bottom row. Kit icons fill the middle rows at their configured slots. Slot 4 (top center) holds an info/summary item [VERIFY]. Bottom-right slot is a red barrier that closes the menu.
- Tooltip for every kit icon:
    Line 1:    (cyan/aqua title)
    Line 2: "⚔  active"   (blue sword icon, white number)
    Line 3: "⚑  queued"   (green flag icon, white number)
    blank line
    "Click to play!"
- If the player is already queued for that kit: the action line becomes "Click to leave queue", and the icon shows the queued state (enchant glint). Title keeps the kit name.
- Counters refresh live while the GUI is open: one batched update per second, in place, only changed lore lines. "active" = players currently inside matches of that kit; "queued" = players waiting in that kit's queue.

# QUEUE BEHAVIOR
- Left click a kit: join that kit's queue. Chat: "Duels » You have joined the  queue." (prefix cyan). The menu stays open (counts update) or closes depending on config `queue.close-on-join` (default: stays open as in the game).
- Click the same kit again, or the queued hotbar item: leave. Chat: "Duels » You have left the  queue."
- Joining a different kit auto-leaves the previous queue: both messages are sent (left old, then joined new).
- While queued the lobby hotbar swaps the Queue item to a "leave queue" item, and the actionbar shows "Queue" with the kit name and elapsed wait time. Restore the normal hotbar on leave/match found/quit.
- A player can only be in one queue. Blocked states: in a match, spectating, already in a party as a non-leader (members cannot queue by themselves), Presence = Do Not Disturb does NOT block queueing but blocks incoming invites. Show a red error message for blocked states.
- Quit, world change, teleport out of lobby, or death in the lobby removes the player from the queue silently (no message spam), counters update immediately.

# MATCHMAKING
- One FIFO queue per kit (+ separate queue for party vs party, interface only; Phase 3 fills it).
- Instant match as soon as two compatible players exist. Compatibility: same kit, not the same player, not recently matched with the same opponent more than N times in a row (config `matchmaking.avoid-repeat`, default 2).
- Ping-aware pairing: prefer the closest ping; widen the allowed ping gap by +10 ms every 5 seconds of waiting (config values), until it is unlimited.
- Ranked kits: optional Elo-window pairing with the same widening rule; unranked kits ignore Elo. Store per-kit Elo in the DB (default 1000).
- On match found: remove both from the queue, restore hotbars, send title "Match found!" + chat line with the opponent name, play a sound, and call `MatchStarter.start(kit, players)`. The stub must be replaceable by Phase 5 without touching the queue code.
- Thread safety: the queue structures are mutated only from one place (a single scheduler context or a concurrent structure with a clear owner). The matchmaker tick runs every 10 ticks, never blocks the main/region thread, and is Folia-safe.

# COMMANDS & PERMISSIONS
/queue [kit] (opens GUI or joins directly), /leavequeue, /vduels kit list|reload. Permissions: vduels.queue, vduels.queue. (default true), vduels.admin.kits. Per-kit permission gating is optional and shows a red error if denied.

# PERSISTENCE
Table kit_stats: uuid, kit_id, elo, wins, losses, streak. Loaded async on login, saved on quit and periodically. Expose `StatsService.getElo(uuid, kit)` for Phase 5.

# MESSAGES
All new strings in messages.yml (MiniMessage), same prefixes as Phase 1: "Duels »" cyan. Keep strings identical to those above.

# PERFORMANCE & SAFETY
- Pre-build kit icon ItemStacks; only rebuild lore when counters change. No per-tick allocations in the matchmaker. Rate-limit queue join/leave clicks (anti-spam). Validate every click server-side. Clean up all queue state on plugin disable.

# DELIVERABLES
1. Source for this phase integrated with Phase 1's packages.
2. kits.yml with the default kits, updated config.yml/messages.yml/guis/queue.yml.
3. MatchStarter interface + stub.
4. Commands, permissions, README section.
5. A test checklist covering: join/leave messages, switching kits, live counters, queued glint, hotbar swap/restore, quit cleanup, ping/Elo widening, repeat-opponent avoidance.
Do not implement parties, the Kit Editor or the actual match; keep the hooks.
Kodari AI
KodariOct 22 at 10:16 pm 4

Plan:

  1. Map Phase 1’s GUI, scheduler, config/message, hotbar, storage, and command conventions.

  2. Implement kit registry, queue/matchmaking, stats and the replaceable match hand-off.

  3. Integrate the queue GUI, commands, lifecycle cleanup, and config defaults.

  4. Add the requested README section and verification checklist.

Implemented Phase 2 using the existing APracticeCore GUI and Folia scheduler patterns.

  • Added the configurable kit registry and Queue GUI, including live counters, queued glint, hotbar swap/restore, join/leave behavior, and queue cleanup.

  • Added FIFO matchmaking with ping and ranked-Elo widening, repeat-opponent avoidance, persisted per-kit stats, and a replaceable MatchStarter stub.

  • Registered /queue, /leavequeue, and /vduels kit list|reload; added permissions, messages, queue GUI config, kit defaults, and a README verification checklist.

  • Left party, match-state, and active-match counting integration hooks for later phases; the stub does not start actual matches.

No videos were attached, so the default kits follow the names in the brief; their GUI slots are configurable.

S
📎 1 file 7,302 chars
📄
pasted-code-1792707437075.txt
txt 66 lines
▶
# ROLE
You are a senior Minecraft plugin engineer. This is PHASE 3 of 5 of the "VDuels" plugin (recreating the Vanilla Practice server experience, vanillapractice.com). Phases 1-2 already exist: core, GuiManager/BaseGui, storage, scoreboard, lobby hotbar, Settings GUIs (Privacy/Display/Account), PresenceService, KitRegistry, QueueManager, Matchmaker, and the MatchStarter interface. Reuse their framework, MessageService, scheduler abstraction and conventions. Do NOT rewrite earlier phases. Implement the Party system with maximum fidelity to the behavior below. Kit Editor and the real match flow come later; keep the hooks.

# TECH STACK (same as before)
Java 21, Paper 1.21.x, Folia-compatible (existing scheduler abstraction), Adventure/MiniMessage, config-driven, /vduels reload supported. Permission prefix vduels.*

# NEW PACKAGES
party (Party, PartyManager, PartyInvite, PartyRole, PartyMode), party.gui (ManagePartyGui, PartyMembersGui, DisbandConfirmGui), party.listener, command.

# GLOBAL UI CONVENTIONS (unchanged)
- All clicks/drags/shift/number-key/offhand swaps cancelled; items non-movable.
- Tooltip: colored title, gray description, blank line, details, blank line, action line.
- Action line: the word "Click" yellow + underlined, rest white.
- Submenu titles start with a colored glyph/back-arrow then the name. Filler panes named "Filler" / "Decorative — players cannot interact".
- Soft click sounds; in-place item updates; no reopen flicker.

# CREATING A PARTY
- The lobby hotbar item "+ Party" (lore "Duel Menu" / "Click to create a party.") creates a party with the clicker as leader. Also /party create.
- On creation: big title "Party Created" (green, bold) + subtitle "/party invite  to invite friends." (gray, the command part highlighted), plus the same info in chat, and a soft level-up sound.
- If the player is already in a party, the item opens Manage Party instead. If they are queued, creating a party auto-leaves the queue (with the usual "You have left the  queue." message).
- Hotbar swap while in a party (slot indexes configurable) [VERIFY exact layout from the videos]: red barrier (leave party / disband for leader), Kit Editor book, Settings nether star, and a black block that opens Manage Party. Restore the normal lobby hotbar when the party ends or the player leaves.

# COMMANDS
/party create | invite  | accept [player] | deny [player] | leave | kick  | promote  | disband | list | chat  | settings. Alias /p. Tab completion for online players and pending invites.
- Invites expire after 60 s (config). Clickable chat message for the invitee: [Accept] green / [Deny] red.
- Respect the Phase 1 settings: Presence = Do Not Disturb blocks incoming party invites (tell the inviter the player is unavailable, without revealing more). Privacy settings for friends-only invites if configured (use the FriendProvider stub).
- Max party size from config (default 8). Errors in red: already in a party, party full, player offline, invite pending, you are not the leader.

# MANAGE PARTY GUI
Title "Manage Party" (cyan icon glyph), 3 rows. Leader-only; non-leaders get a read-only view (action items show a red "Only the party leader can do this."). Items [VERIFY exact slots from the videos; keep them configurable]:
  - Info scroll (top center): party summary — leader, member count, mode, advertised status.
  - Two chestplate items (iron and blue) on the left-center: party mode selection (e.g. FFA vs Teams / split) with the active one glowing; click switches mode and confirms in chat. [VERIFY exact meaning]
  - Advertise Party (firework/torch item): broadcasts a clickable "'s party is open — click to join" message to the lobby with a cooldown (config, default 60 s). Requires permission vduels.party.advertise. If the player lacks it, the tooltip becomes a red "✖ Advertise Party" with the gray line "Requires the vduels.party.advertise permission." (with an info glyph) and the click does nothing.
  - Party Members (ender-eye style item): "Party Members" / " in your party" (e.g. "1 in your party") / blank / "Click to view everyone." -> opens PartyMembersGui.
  - Disband Party (red barrier, bottom center): red title "Disband Party" / gray "Sends everyone home" / blank / "Click to disband." -> opens the confirmation GUI.

# PARTY MEMBERS GUI
Player heads with name; leader gets a crown suffix. For the leader, clicking a member head offers kick (with a "Click to kick" action line), shift-click promotes. Includes a back button to Manage Party.

# DISBAND CONFIRMATION GUI
Title "✖ Disband Party?" (red X, pink/red text). 3 rows. Confirm item (cake/donut) placed left-center; red barrier "Cancel" with gray "Keep the party." placed on the right side. Confirm: disband the party, teleport every member to lobby spawn (respecting spawn preference), reset hotbars, send "Party disbanded." to all. Cancel: back to Manage Party.

# PARTY BEHAVIOR
- Leader leaves: promote the longest-standing member automatically, or disband if alone. Config option.
- Member quits: remove after a 30 s reconnect grace period (config); leader quit triggers the promotion rule.
- Party chat via /party chat or a prefix character (config). Format: "Party » : " with a distinct color.
- All party members teleport together when the leader queues or starts a match; members cannot queue on their own (the Phase 2 block is enforced here).
- Party Queue: the leader queues a kit from the Queue GUI; the whole party enters the party queue for that kit. Implement party vs party pairing inside the Phase 2 Matchmaker using the reserved interface (match sizes must be equal; FFA mode allows N vs N or free-for-all as configured). On match found, call MatchStarter.start(kit, teams).
- If any member becomes unavailable (offline, in a match), the party queue entry is cancelled with a clear message to the leader.
- Spectators and players in a match cannot create or join parties.

# PERSISTENCE
Parties are in-memory only (cleared on restart). Persist only party-related player settings if any are added.

# MESSAGES
All strings in messages.yml (MiniMessage). Prefix "Party »" (purple/light-purple), errors red, success green. Keep titles and tooltip strings identical to the ones above.

# PERFORMANCE & SAFETY
- Thread-safe party registry with a single owner context (Folia-safe). Cache GUI items; update only changed slots. Rate-limit invites (config) and advertise. Validate permissions and leadership on every click server-side. Clean up invites, hotbars and queue entries on quit/disable.

# DELIVERABLES
1. Source for this phase integrated with the existing packages.
2. Updated config.yml, messages.yml, guis/manage-party.yml, guis/party-members.yml, guis/disband-party.yml.
3. Commands, permissions (vduels.party, vduels.party.advertise, vduels.party.create) and README section.
4. A test checklist covering: create/title text, invite/accept/deny/expiry, DND block, full party, mode switch, advertise with and without permission (red tooltip), member list, kick/promote, disband confirm/cancel, leader leave/quit promotion, hotbar swap/restore, party queue hand-off.
Do not implement the Kit Editor or the real match; keep the hooks.
Kodari AI
KodariOct 22 at 11:05 pm 9
  1. Map the existing plugin APIs and conventions the party system must integrate with.

  2. Implement party state, invites, commands, and lifecycle behavior using those APIs.

  3. Add party GUIs, hotbar/queue hooks, and config/message resources.

  4. Add permissions, README guidance, and the requested test checklist.

  • Add party state, invites, lifecycle handling, permissions, and /party//p commands.

  • Connect party hotbars and party-vs-party queues to the existing queue/match handoff.

  • Add the three configured GUIs and party-specific messages/settings.

  • Document the new commands and the Phase 3 verification checklist.

Implemented the Phase 3 party system and integrated it with the existing VDuels framework.

  • Added party creation, clickable invites with expiry, DND and configurable friends-only checks, promotion, reconnect grace, party chat, and party hotbar handling.

  • Added /party and /p commands with tab completion and the requested party permissions.

  • Added configurable Manage Party, Party Members, and disband-confirmation GUIs under party.gui, including leader-only actions and the advertise permission tooltip.

  • Connected party queues to the existing Matchmaker and team-roster MatchStarter hook, with configurable FFA behavior. Real match gameplay remains a stub for the later phase.

  • Updated config, messages, GUI resources, and the README with the Phase 3 verification checklist.

S
📎 1 file 10,296 chars
📄
pasted-code-1792715240680.txt
txt 82 lines
▶
# ROLE
You are a senior Minecraft plugin engineer. This is PHASE 4 of 5 of the "VDuels" plugin (recreating the Vanilla Practice server experience, vanillapractice.com). Phases 1-3 already exist: core, GuiManager/BaseGui, storage, lobby hotbar, Settings, KitRegistry + kits.yml, QueueManager, Matchmaker, Party system, MatchStarter interface. Reuse their framework, MessageService, scheduler abstraction and conventions. Do NOT rewrite earlier phases. Implement the Kit Editor with maximum fidelity to the behavior below. The real match flow comes in Phase 5; expose a clean API so it can apply a player's saved layout.

# TECH STACK (same as before)
Java 21, Paper 1.21.x, Folia-compatible (existing scheduler abstraction), Adventure/MiniMessage, async DB I/O, config-driven, /vduels reload supported. Permission prefix vduels.*

# NEW PACKAGES
kit.editor (KitEditorSession, KitEditorGui, PaletteCategory, PaletteItem), kit.enchant (EnchantGui, EnchantRules), kit.trim (TrimGui), kit.preset (SavedKitsGui, KitPreset), kit.validate (KitValidator), storage additions (PlayerKitLayout).

# GLOBAL UI CONVENTIONS (unchanged)
- All clicks/drags/shift/number-key/offhand swaps cancelled unless explicitly part of the editor's layout interaction (see below). Items in plugin-owned slots are non-movable.
- Tooltip: colored title, gray description, blank line, details, blank line, action line.
- Action line: the word "Click" yellow + underlined, rest white.
- Filler panes are named "Filler" with description "Decorative — players cannot interact" (italic gray).
- Soft click sounds; in-place item updates; no reopen flicker.

# ENTRY FLOW
1. Lobby hotbar Kit Editor item (book; actionbar text "Kit Editor") or /kiteditor -> Kit Select GUI.
2. Kit Select GUI: same layout and icons as the Queue GUI (blue stained-glass Filler border, kit icons at their configured slots, red barrier at bottom-right). Tooltip per kit: colored kit name (with icon glyph), gray "Duel Menu", blank line, "Click to edit your kit."  (No active/queued counters here.)
3. Click a kit -> Kit Editor GUI for that kit. Blocked while queued, in a match or spectating (red error). Members of a party can use it freely.

# KIT EDITOR GUI (the main screen)
Title "Kit Editor". A 5-row top inventory plus the player's own inventory below it, used as one combined editing surface:
- Top GUI, rows 1-3 (27 slots): the ITEM PALETTE for the currently selected category (see below). Palette items are pre-built and pre-enchanted according to the kit's rules (e.g. netherite sword with Sharpness V, Sweeping Edge III, Knockback I, Looting III, Unbreaking III). Items show full vanilla tooltips including attribute lines ("When in Main Hand: 8 Attack Damage / 1.6 Attack Speed", "When on Head: +3 Armor ...").
- Right column of the top GUI: CATEGORY TABS, icons such as a sword (weapons/gear), an emerald (blocks/utility), and a potion (Consumables). The selected tab glows. Tooltip example: yellow "Consumables", then " items" in gray (e.g. "5 items"), then cyan "Selected" when active. Click switches the palette in place.
- Top GUI, bottom row (row 5): ARMOR + OFFHAND + BUTTONS, left to right: boots, leggings, chestplate, helmet, offhand (Totem of Undying), then a gap, then three buttons:
    - "✦ Saved Kits" (magenta) — gray "Click to open kit presets" -> SavedKitsGui.
    - Reset/clear layout book (red book) — resets the layout to the kit default (ask for a confirmation click).
    - Red barrier "Close" — "Click to save and close."
- Bottom area (the player's real inventory, 36 slots incl. hotbar): the KIT LAYOUT. It is pre-filled with the player's saved layout (or the kit default). Items here use normal vanilla stack counts (64, 16, etc.).

# EDITING MECHANICS
- Left-click a palette item with an empty cursor: pick up a COPY (palette never depletes). Click an empty/any layout slot to place it. Shift-click a palette item: send it to the first free layout slot (hotbar first).
- Drag items inside the layout area to rearrange (allowed only within the layout, armor row and offhand). Dropping an item outside, on a Filler or a button is cancelled and returns it.
- Right-click a layout item with an empty cursor: split stack; clicking an item with the number keys 1-9 moves it to that hotbar slot (allowed inside the layout only).
- Dragging a palette item onto an armor slot only works if the item is the right armor type; wrong type is rejected with a soft error sound.
- Remove an item: pick it up and drop it onto the palette area (deletes it) or press the drop key (deletes it, never spawns an entity).
- Stack limits come from the kit rules (e.g. max 64 totems total, max N crystals, max N golden apples, max N ender pearls). Exceeding a limit rejects the placement with a red actionbar message "Limit reached for ."
- Right-click the cursor is never used to place items into the Filler panes.

# ENCHANT GUI
- On an armor piece or weapon in the layout or palette: Left-click opens the Enchant GUI; Right-click opens the Trim GUI (armor only). The item's tooltip must end with:
    "Click (left) for enchants."  "Click (right) for trim."  (action words yellow underlined)
- Enchant GUI (title is the item name or "Enchants"; 5 rows): the top rows show pink enchanted books, one per applicable enchantment (respecting the kit rules: Protection IV, Respiration III, Aqua Affinity, Unbreaking III, Mending, Curse of Vanishing, Sharpness V, Sweeping Edge III, Knockback I, Looting III, Riptide III, Impaling V, Wind Burst III, Density V, etc.).
- Book states: an applied enchant shows yellow title " " (e.g. "Unbreaking 3"), a white line with the vanilla name ("Unbreaking III"), a green line "Applied — level ", blank line, and a red line "Click to remove". Not-applied books show the max/next level and "Click to apply".
- Left-click a book: apply or cycle the level up to the allowed max; right-click lowers/removes. Incompatible enchants (e.g. Sharpness vs Smite, Protection types) automatically remove each other with a small notice. Curse of Vanishing shows in red.
- Bottom row: the item being edited (preview, updates live), a gray "Clear Enchants" button (red title, "Click to remove every enchant."), a green confirm/back pane, and back navigation. Closing returns to the Kit Editor with the item updated in the layout.
- Item tooltips must show the real final enchant list and attribute lines.

# TRIM GUI
Armor only. Two pages or two rows: pattern picker (all vanilla trim patterns) and material picker (all trim materials). Live preview of the armor piece. "Clear Trim" button and Back. Respect kit rules (can disable trims).

# SAVED KITS (PRESETS)
- Title "Saved Kits" (magenta glyph). Several preset slots per kit (config, default 5). Each slot shows a name, last-saved info and a small icon preview line.
- Left-click an empty slot: save the current layout into it. Left-click a filled slot: load it into the editor (confirmation click if the current layout is unsaved). Right-click: rename (anvil/chat prompt). Shift-click: delete (confirmation). One preset can be marked "Active" and is what the match uses; it is shown with a glint and a green "Active" line.
- Back button returns to the Kit Editor.

# SAVE, CLOSE AND VALIDATION
- Closing the editor by the "Close" barrier OR by pressing Esc saves automatically. Chat: "Kit saved." (green) and the actionbar returns to "Kit Editor".
- KitValidator runs on every save AND every time the layout is applied in Phase 5: whitelist of materials, enchant caps, stack sizes, per-item totals, no custom NBT/PDC from clients, no unbreakable-flag exploits, no illegal potions/arrows beyond the palette set (e.g. "Arrow of Slow Falling (00:30)" is allowed), armor in armor slots only. Invalid data is silently reduced to legal limits and the player is told what was adjusted.
- Palette is generated from kits.yml rules, so each kit exposes only its own legal items (e.g. totems, firework rockets with Flight Duration 3, end crystals, respawn anchors, obsidian, glowstone, ender pearls, golden apples, potions, food, blocks, elytra, trident, mace, crossbow, bow, netherite gear).
- The player's real inventory is snapshot-saved BEFORE opening the editor and restored on close, so nothing is lost on crash/quit (persist the snapshot to the DB). Quitting inside the editor saves the layout and restores the lobby inventory on next login.

# API FOR PHASE 5
`KitLayoutService.getActiveLayout(uuid, kitId)` returns a validated layout (armor, offhand, 36 slots, enchants, trims). `KitLayoutService.apply(player, kit)` applies it to the player at match start. Layouts are cached per player and loaded async on login.

# PERSISTENCE
Table kit_layouts: uuid, kit_id, preset_index, name, active, layout_blob (compact serialized items: material, amount, enchants, trim, potion data), updated_at. Table inventory_snapshots for the editor safety net. All DB access async.

# MESSAGES
All strings in messages.yml (MiniMessage). Prefix "Kit Editor »" (aqua). Errors red, success green. Keep all titles and tooltip strings identical to the ones above.

# PERFORMANCE & SAFETY
- Pre-build palette ItemStacks per kit and category; cache them. Update only changed slots. Rate-limit saves and preset operations. Validate every click server-side. Handle edge cases: inventory full, cursor items on close, shift-click spam, double-click collect, drag across GUI boundary, creative-mode clients. Close all editor GUIs on world change, teleport, queue join and quit.

# DELIVERABLES
1. Source for this phase integrated with the existing packages.
2. Updated kits.yml (palette + rules per kit), config.yml, messages.yml, guis/kit-select.yml, guis/kit-editor.yml, guis/enchant.yml, guis/trim.yml, guis/saved-kits.yml.
3. Commands: /kiteditor [kit]; permissions vduels.kiteditor and vduels.kiteditor.presets.
4. KitLayoutService API + README section.
5. A test checklist covering: category switching, copy-pick placement, limits, armor-type checks, enchant apply/remove/conflicts, tooltips with attribute lines, trims, presets save/load/rename/delete/active, auto-save on Esc, snapshot restore after crash, validator clamping.
Do not implement the real match; leave the API ready.
Kodari AI
KodariOct 23 at 1:09 am 45
  1. Map existing kit, GUI, storage, command, and lifecycle APIs to avoid rewriting earlier phases.

  2. Add layout data, validation, async persistence, and the Phase 5 KitLayoutService API.

  3. Build editor, enchant, trim, preset, and kit-select interactions using the existing GUI framework.

  4. Wire commands/config/messages, safety lifecycle hooks, and provide the requested README/test checklist.

Task 2 — foundation:

  • Add a validated layout/preset record and persist layouts plus editor safety snapshots through the existing SQL storage abstraction.

  • Add KitValidator and a cached KitLayoutService with the requested synchronous match-start API and async DB loading/saving.

  • Register the service in the plugin lifecycle without changing existing kit or match behavior.

  1. The editor, kit selector, enchant/trim screens, preset screen, and combined inventory interactions are in place. Next I’m wiring their resources, command, login/safety hooks, and checklist into the existing lifecycle.

I’m aligning the editor screens with the requested kit.editor, kit.enchant, kit.trim, and kit.preset packages before the final wiring pass.

Implemented Phase 4 without changing the match flow.

  • Added per-kit layouts and presets in kit_layouts, editor safety snapshots in inventory_snapshots, and the Phase 5 KitLayoutService.getActiveLayout(uuid, kitId) / apply(player, kit) API.

  • Added the kit selector, combined layout editor, enchant and trim screens, and saved-kit workflow. Layouts are validated on save and apply; the editor snapshot is persisted before the editor opens.

  • Wired /kiteditor [kit], permissions, the lobby hotbar entry, and cleanup for Escape, quit, teleport, world change, and successful queue joins.

  • Added palette, enchantment, potion, firework, GUI, message, and editor configuration, plus the requested verification checklist in README.md.

S
📎 1 file 9,068 chars
📄
pasted-code-1792724778350.txt
txt 67 lines
▶
# ROLE
You are a senior Minecraft plugin engineer. This is PHASE 5 of 5 (final) of the "VDuels" plugin (recreating the Vanilla Practice server experience, vanillapractice.com). Phases 1-4 already exist: core, GuiManager/BaseGui, storage, lobby hotbar/scoreboard/actionbar, Settings (PresenceService, Fast Crystals flag, spawn preference), KitRegistry + kits.yml, QueueManager + Matchmaker, Party system, Kit Editor with KitLayoutService, and the MatchStarter interface (currently a stub). Reuse their framework, MessageService, scheduler abstraction and conventions. Do NOT rewrite earlier phases. Replace the MatchStarter stub with the real match system, then polish and harden the whole plugin.
NOTE: the match phase was not shown in the reference videos, so implement standard, polished practice-server behavior and keep every string, color and prefix consistent with the earlier phases. Make every timing, message and rule configurable.

# TECH STACK (same as before)
Java 21, Paper 1.21.x, Folia-compatible (existing scheduler abstraction; every world/entity operation on the correct region/entity scheduler), Adventure/MiniMessage, async DB I/O, config-driven, /vduels reload supported. Permission prefix vduels.*

# NEW PACKAGES
match (Match, MatchManager, MatchState, MatchTeam, MatchListener, MatchStarterImpl), arena (Arena, ArenaTemplate, ArenaPool, ArenaCopier), spectate (SpectatorManager, SpectatorGui), result (MatchResult, ResultService, EloCalculator), rematch, plus admin tools.

# GLOBAL UI CONVENTIONS (unchanged)
- Plugin GUIs cancel all clicks/drags; tooltip format: colored title, gray description, blank line, details, blank line, action line ("Click" yellow + underlined).
- Prefixes: "Duels »" cyan, errors red, success green.

# MATCH LIFECYCLE
States: STARTING -> COUNTDOWN -> ACTIVE -> ENDING -> CLEANUP.
1. STARTING (called by MatchStarter.start(kit, teams) from the Matchmaker, solo or party): reserve a free arena, abort cleanly with a red message and requeue if none is available within a timeout.
2. Teleport all players to their team spawn points (async chunk load first, then teleport on the correct scheduler). Clear effects, fire, fall damage, set full health/food/saturation, game mode survival, remove them from queue/party-queue state. Lobby hotbar/scoreboard switch to match mode.
3. Apply the kit: KitLayoutService.apply(player, kit) using each player's active preset (validated). Fall back to the kit default layout if none/invalid.
4. COUNTDOWN 5 seconds: players frozen (cancel movement but allow looking), big title with the number (5..1) + tick sound, then "GO!" (green) with a higher sound. Chat line "Duels » Match starting against  in ." No damage or item use during countdown.
5. ACTIVE: normal combat per kit rules (hunger, natural regen, build/break on/off, crystals, anchors, mace, tridents, elytra, ender pearls, totems). Match timer (config, default 15 min) shown in the scoreboard/actionbar. Time-out = draw (config: or sudden death).
6. Death handling: no death screen. On lethal damage cancel death, set the player to spectator at their location, drop nothing, play a sound, show a "You were defeated" title (red), broadcast to participants " was slain by ." (config for cause variants). When a team has no players left alive the other team wins.
7. Disconnect = forfeit after 10 s grace (config) ; leaving the arena bounds = defeat after a warning (config).
8. ENDING (5 s): winner title "VICTORY" (green) / loser "DEFEAT" (red) / "DRAW" (yellow); fireworks for winners; stats screen in chat (see Results). Then teleport everyone back to lobby spawn (respecting Spawn Preference), restore lobby inventory/hotbar/scoreboard, party members return together.
9. CLEANUP: reset the arena, free it in the pool, clear drops/entities/projectiles, remove all match references (no leaks).

# ARENAS
- Admin commands: /vduels arena create|setspawn <1|2>|setcorner <1|2>|setkit|enable|disable|list|delete|tp|paste. Arena template stored per kit (a kit can have many arenas).
- ArenaPool with instant copy/reset: copy template into a free slot area (schematic-free or via your own block-snapshot method, async/chunk-friendly, Folia-safe), many concurrent matches, config limit. Reset = restore the snapshot of changed blocks only (track block changes) for speed. Entities and dropped items are cleared on reset.
- Arena bounds enforced: build height, no-build zones, void kill, border warning actionbar.
- Per-kit rules from kits.yml decide whether blocks are placeable/breakable and which blocks are restored.

# RESULTS, STATS AND PROGRESSION
- Chat result box at the end: winner(s), loser(s), kit, duration, health left (hearts), potions/pearls/totems used (if tracked), and clickable [Rematch] and [Play Again] buttons.
- Update stats: Kills (+1 per kill, shown in the Phase 1 scoreboard), Coins (win/loss rewards, configurable), Level/XP (level-up message and title), per-kit wins/losses/streak, Elo for ranked kits (EloCalculator with K-factor config, shown as "+15 / -12"). All DB writes async and batched.
- Anti-boost: no stats/Elo if the same two players have played more than N times in a row within a time window (config), minimum match duration for rewards.

# SPECTATING
- /spectate  and a Spectate action in the lobby (optional). Players in spectator mode (dead participants and outsiders) can fly, teleport via a spectator menu GUI (heads of alive players), cannot interact, and are hidden from participants (hide via Player#hidePlayer). Spectators see a leave item and "Match" scoreboard info. Config option to disable outsider spectating and respect Presence = Do Not Disturb.

# REMATCH
- Clickable [Rematch] in the result box and a hotbar rematch item for 30 s (config). Both players must accept; if so, create a new match with the same kit/arena rules. Expires with a clear message. Not available if either player is queued/in a party mismatch.

# INTEGRATIONS WITH EARLIER PHASES
- Queue: replace the MatchStarter stub, update the live " active" counters from running matches (feed StatsService), remove players from queues when a match starts.
- Party: team matches use party members as teams (FFA mode if configured), the leader's queue controls it, members cannot leave mid-match without forfeit, disband during a match is blocked.
- Settings: Presence DND blocks rematch/spectate invites, Join/Leave and Announcement settings are respected, Fast Crystals flag speeds end-crystal place/break handling in matches with the sanity checks from Phase 1.
- Kit Editor: editor and settings menus are unavailable during a match; the layout is applied via the Phase 4 API and validated again.

# ADMIN AND OPERATIONS
- /vduels match list|end |spectate , /vduels stats  [kit], /vduels setcoins|setlevel (permissioned), /vduels debug. Metrics: matches running, arenas free, average queue time, TPS-safe task budget logging.
- Graceful shutdown: end all matches as draws, restore all inventories, reset arenas, flush stats.
- Crash safety: on login, if a player has a leftover match/inventory snapshot, restore it and send them to lobby.

# POLISH AND HARDENING (applies to the whole plugin)
- Review all phases for consistency: identical wording, colors and prefixes everywhere; no hard-coded strings outside messages.yml; every GUI item pre-built and cached; only changed slots updated.
- Performance: zero blocking I/O on main/region threads, no per-tick allocations in hot paths, batched DB writes, bounded caches, cleanup on quit/disable. Test with 100+ simulated players and 25+ concurrent matches.
- Security: validate every click and command server-side, permission checks everywhere, rate limits (queue, invites, rematch, kit saves), item/dupe protection, no client-trusted data.
- Compatibility: Paper 1.21.x and Folia; soft-depend integrations (PlaceholderAPI expansion with %vduels_kills%, %vduels_level%, %vduels_coins%, %vduels_elo_%, %vduels_queued%, %vduels_active%).
- Add a bStats-free, privacy-friendly build; optional update checker disabled by default.

# DELIVERABLES
1. Source for this phase integrated with Phases 1-4 and a final cleanup/consistency pass over the whole codebase.
2. kits.yml final rules, arenas.yml, config.yml, messages.yml, guis/spectator.yml.
3. Commands, permissions (vduels.admin.arena, vduels.spectate, vduels.admin.match, vduels.admin.stats) and a complete README (install, commands, permissions, config reference, PlaceholderAPI).
4. A full end-to-end test checklist: queue -> match found -> teleport -> kit applied from the player's preset -> countdown -> combat -> death handling -> win/lose/draw -> stats/Elo/coins -> return to lobby -> rematch -> spectate -> disconnect/forfeit -> arena reset -> shutdown recovery; plus party matches and every Phase 1-4 tooltip/message regression check.
5. Final summary of any assumptions and the remaining [VERIFY] items from Phases 1-4 so they can be compared with the original server.
Kodari AI
KodariOct 23 at 3:54 am 31
  1. Map the existing match stub and the queue, kit, scheduler, and plugin lifecycle APIs it must integrate with.

  2. Implement the match lifecycle using those existing conventions, then add supporting arena/results/spectate features in focused increments.

  3. Update configs, commands, and documentation only where the project structure supports them; report any remaining verification gaps.

Implemented the phase-5 match path: the stub is replaced with arena waiting and requeue, snapshots and kit application, countdown, active timer, combat/death handling, disconnect grace, bounds warnings, results, Elo/rewards, rematches, spectating, party lockouts, and admin commands. Added arenas.yml, spectator GUI/config, PlaceholderAPI placeholders, permissions, messages, and an expanded README with an end-to-end and phase 1–4 regression checklist.

Important limits: arenas are fixed physical rooms; template copying and /vduels arena paste are not implemented. Full entity/projectile cleanup, all specialized kit-item rules, a spectator scoreboard, and the rematch hotbar item also remain incomplete. These limits and [VERIFY] items are documented in README.md.

No live Paper/Folia integration test was run; use the README checklist to validate the target server behavior.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle.kts
manifest.kod
README.md
settings.gradle.kts
Code
103 9,159
src/main/java/nya/AnunglT/Apracticecore/APracticeCore.java
package nya.AnunglT.Apracticecore;

import nya.AnunglT.Apracticecore.command.SettingsCommand;
import nya.AnunglT.Apracticecore.command.VDuelsCommand;
import nya.AnunglT.Apracticecore.gui.GuiListener;
import nya.AnunglT.Apracticecore.gui.GuiManager;
import nya.AnunglT.Apracticecore.lobby.LobbyHud;
import nya.AnunglT.Apracticecore.lobby.LobbyListener;
import nya.AnunglT.Apracticecore.listener.PlayerDataListener;
import nya.AnunglT.Apracticecore.listener.QueueListener;
import nya.AnunglT.Apracticecore.listener.RequestEnforcementListener;
import nya.AnunglT.Apracticecore.kit.KitRegistry;
import nya.AnunglT.Apracticecore.kit.KitLayoutService;
import nya.AnunglT.Apracticecore.queue.QueueManager;
import nya.AnunglT.Apracticecore.queue.MatchStarterImpl;
import nya.AnunglT.Apracticecore.queue.MatchStarter;
import nya.AnunglT.Apracticecore.match.MatchListener;
import nya.AnunglT.Apracticecore.match.MatchManager;
import nya.AnunglT.Apracticecore.party.PartyManager;
import nya.AnunglT.Apracticecore.party.listener.PartyListener;
import nya.AnunglT.Apracticecore.command.PartyCommand;
import nya.AnunglT.Apracticecore.command.KitEditorCommand;
import nya.AnunglT.Apracticecore.listener.KitEditorListener;
import nya.AnunglT.Apracticecore.arena.ArenaPool;
import nya.AnunglT.Apracticecore.spectate.SpectatorManager;
import nya.AnunglT.Apracticecore.command.SpectateCommand;
import nya.AnunglT.Apracticecore.command.RematchCommand;
import nya.AnunglT.Apracticecore.settings.FriendProvider;
import nya.AnunglT.Apracticecore.settings.PresenceService;
import nya.AnunglT.Apracticecore.settings.StubFriendProvider;
import nya.AnunglT.Apracticecore.stats.StatsService;
import nya.AnunglT.Apracticecore.storage.PlayerData;
import nya.AnunglT.Apracticecore.storage.PlayerSettings;
import nya.AnunglT.Apracticecore.storage.PlayerStorage;
import nya.AnunglT.Apracticecore.storage.SqlPlayerStorage;
import nya.AnunglT.Apracticecore.rematch.RematchManager;
import nya.AnunglT.Apracticecore.placeholder.VDuelsPlaceholderExpansion;
import nya.AnunglT.Apracticecore.util.TaskScheduler;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class APracticeCore extends JavaPlugin {
    private final Map<UUID, PlayerData> playerData = new ConcurrentHashMap<>();
    private final Map<String, FileConfiguration> guiConfigs = new ConcurrentHashMap<>();
    private FileConfiguration messageConfig;
    private FileConfiguration kitConfig;
    private PlayerStorage storage;
    private GuiManager guiManager;
    private LobbyHud lobbyHud;
    private FriendProvider friendProvider;
    private PresenceService presenceService;
    private KitRegistry kitRegistry;
    private KitLayoutService kitLayoutService;
    private StatsService statsService;
    private QueueManager queueManager;
    private MatchStarter matchStarter;
    private MatchManager matchManager;
    private ArenaPool arenaPool;
    private SpectatorManager spectatorManager;
    private RematchManager rematchManager;
    private PartyManager partyManager;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        saveResource("messages.yml", false);
        saveResource("kits.yml", false);
        saveResource("arenas.yml", false);
        for (String gui : new String[]{"settings", "privacy", "display", "account", "queue", "manage-party", "party-members", "disband-party", "kit-select", "kit-editor", "enchant", "trim", "saved-kits", "spectator"}) saveResource("guis/" + gui + ".yml", false);
        reloadPluginConfigs();
        storage = new SqlPlayerStorage(this);
        guiManager = new GuiManager(this);
        friendProvider = new StubFriendProvider();
        presenceService = new PresenceService(this);
        kitRegistry = new KitRegistry(this);
        kitLayoutService = new KitLayoutService(this);
        statsService = new StatsService(this);
        arenaPool = new ArenaPool(this);
        matchManager = new MatchManager(this);
        matchStarter = new MatchStarterImpl(this);
        queueManager = new QueueManager(this, kitRegistry, statsService, matchStarter);
        partyManager = new PartyManager(this);
        queueManager.setPartyQueue(partyManager);
        spectatorManager = new SpectatorManager(this);
        rematchManager = new RematchManager(this);
        lobbyHud = new LobbyHud(this);
        Bukkit.getPluginManager().registerEvents(new GuiListener(guiManager), this);
        Bukkit.getPluginManager().registerEvents(new PlayerDataListener(this), this);
        Bukkit.getPluginManager().registerEvents(new LobbyListener(this), this);
        Bukkit.getPluginManager().registerEvents(new RequestEnforcementListener(this), this);
        Bukkit.getPluginManager().registerEvents(new QueueListener(this), this);
        Bukkit.getPluginManager().registerEvents(new PartyListener(this), this);
        Bukkit.getPluginManager().registerEvents(new KitEditorListener(this), this);
        Bukkit.getPluginManager().registerEvents(new MatchListener(this), this);
        getCommand("settings").setExecutor(new SettingsCommand(this));
        getCommand("vduels").setExecutor(new VDuelsCommand(this));
        getCommand("queue").setExecutor(new nya.AnunglT.Apracticecore.command.QueueCommand(this));
        getCommand("leavequeue").setExecutor(new nya.AnunglT.Apracticecore.command.LeaveQueueCommand(this));
        PartyCommand partyCommand = new PartyCommand(this);
        getCommand("party").setExecutor(partyCommand);
        getCommand("party").setTabCompleter(partyCommand);
        getCommand("kiteditor").setExecutor(new KitEditorCommand(this));
        getCommand("spectate").setExecutor(new SpectateCommand(this));
        getCommand("rematch").setExecutor(new RematchCommand(this));
        if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) new VDuelsPlaceholderExpansion(this).register();
        TaskScheduler.globalRepeating(this, this::saveAll, 5, 5, TimeUnit.MINUTES);
    }

    @Override
    public void onDisable() {
        if (matchManager != null) matchManager.shutdown();
        if (partyManager != null) partyManager.shutdown();
        if (queueManager != null) queueManager.shutdown();
        if (storage != null) {
            TaskScheduler.async(this, () -> {
                saveAll();
                storage.close();
            });
        }
    }

    public void reloadPluginConfigs() {
        reloadConfig();
        File messages = new File(getDataFolder(), "messages.yml");
        messageConfig = YamlConfiguration.loadConfiguration(messages);
        for (String gui : new String[]{"settings", "privacy", "display", "account", "queue", "manage-party", "party-members", "disband-party", "kit-select", "kit-editor", "enchant", "trim", "saved-kits", "spectator"}) {
            File file = new File(getDataFolder(), "guis/" + gui + ".yml");
            guiConfigs.put(gui, YamlConfiguration.loadConfiguration(file));
        }
        kitConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "kits.yml"));
        if (kitRegistry != null) kitRegistry.reload();
        if (arenaPool != null) arenaPool.reload();
    }

    public PlayerData data(UUID uuid) {
        return playerData.computeIfAbsent(uuid, id -> new PlayerData(id, "Unknown"));
    }

    public void putData(PlayerData data) { playerData.put(data.getUuid(), data); }
    public void removeData(UUID uuid) { playerData.remove(uuid); }
    public PlayerStorage storage() { return storage; }
    public GuiManager guiManager() { return guiManager; }
    public LobbyHud lobbyHud() { return lobbyHud; }
    public FriendProvider friendProvider() { return friendProvider; }
    public void setFriendProvider(FriendProvider friendProvider) { this.friendProvider = friendProvider; }
    public PresenceService presenceService() { return presenceService; }
    public KitRegistry kitRegistry() { return kitRegistry; }
    public KitLayoutService kitLayoutService() { return kitLayoutService; }
    public StatsService statsService() { return statsService; }
    public QueueManager queueManager() { return queueManager; }
    public MatchStarter matchStarter() { return matchStarter; }
    public MatchManager matchManager() { return matchManager; }
    public ArenaPool arenaPool() { return arenaPool; }
    public SpectatorManager spectatorManager() { return spectatorManager; }
    public RematchManager rematchManager() { return rematchManager; }
    public PartyManager partyManager() { return partyManager; }
    public FileConfiguration kits() { return kitConfig; }
    public FileConfiguration messages() { return messageConfig; }
    public FileConfiguration guiConfig(String key) { return guiConfigs.getOrDefault(key, new YamlConfiguration()); }

    public Map<String, Object> locationMap(Location location) {
        Map<String, Object> values = new java.util.HashMap<>();
        values.put("world", location.getWorld().getName());
        values.put("x", location.getX());
        values.put("y", location.getY());
        values.put("z", location.getZ());
        values.put("yaw", location.getYaw());
        values.put("pitch", location.getPitch());
        return values;
    }

    public Location spawn(PlayerSettings.SpawnPreference preference) {
        String path = "spawns." + preference.name().toLowerCase();
        if (!getConfig().isConfigurationSection(path)) return null;
        var section = getConfig().getConfigurationSection(path);
        World world = Bukkit.getWorld(section.getString("world", ""));
        if (world == null) return null;
        return new Location(world, section.getDouble("x"), section.getDouble("y"), section.getDouble("z"), (float) section.getDouble("yaw"), (float) section.getDouble("pitch"));
    }

    public void saveAsync(PlayerData data) {
        TaskScheduler.async(this, () -> {
            try { storage.save(data); } catch (SQLException exception) { getLogger().warning("Could not save " + data.getName() + ": " + exception.getMessage()); }
        });
    }

    public void saveConfigAsync() {
        TaskScheduler.async(this, this::saveConfig);
    }