a_mo5
๐Ÿ“Ž 1 file 15,847 chars
๐Ÿ“„
pasted-code-1789074403095.txt
txt 950 lines
โ–ถ
You are an expert Minecraft Java plugin developer.

Build a complete production-ready Minecraft cosmetics plugin from scratch.

## Project Information

Plugin name:
`mCosmetics`

Author:
`Moody - _Yasta`

Target:

* Paper 1.21.11
* Java 21
* Maven
* PlaceholderAPI support
* PlayerPoints support
* No NMS unless absolutely necessary
* Clean human-written code
* Do not make the code look AI-generated
* Do not add unnecessary comments
* Use comments only when they are genuinely useful

The plugin must be standalone and must NOT require another cosmetics plugin.

The main goal is to create a highly configurable cosmetics system that can be expanded later without rewriting the entire plugin.

---

# 1. Cosmetics Types

The plugin must support exactly these cosmetic categories initially:

### Particles

Examples:

* Flame
* Heart
* Cloud
* Soul Fire Flame
* Enchant
* End Rod
* Totem
* Snowflake
* Portal
* Crit
* Witch
* Electric Spark

Players can equip one particle effect at a time.

The particle system must be designed so new particle cosmetics can easily be added later.

---

### Arrow Effects

Effects that appear around arrows/projectiles fired by the player.

Examples:

* Flame
* Hearts
* Critical
* Smoke
* End Rod
* Soul
* Enchant

Detect projectiles shot by players and apply the equipped arrow effect.

Make the system configurable and optimized.

---

### Death Effects

When the player kills another player, or when the configured death condition happens, play a cosmetic effect at the victim's location.

Examples:

* Lightning
* Explosion particles
* Hearts
* Flames
* Soul flames
* Totem
* Firework-style effects

Each effect should be independently configurable.

---

### Kill Effects

When a player kills another player, trigger the equipped kill effect.

Examples:

* Lightning
* Blood-style particles using Minecraft particles only
* Fire
* Explosion
* Hearts
* Soul
* Totem
* Ender
* Firework

The killer should be able to equip one Kill Effect.

Do not use external resource packs.

---

### Glow

Allow players to equip a glow color.

Examples:

* White
* Red
* Orange
* Yellow
* Green
* Aqua
* Blue
* Purple
* Pink

Use the Bukkit/Paper scoreboard team glow mechanism where possible.

Do not interfere with the player's existing scoreboard/team system.

The glow system must be implemented safely so it does not randomly break TAB, nametags, or other plugins.

---

### Chat Colors

Allow players to unlock and equip chat colors.

Examples:

```yaml
white: "&f"
gray: "&7"
red: "&c"
dark_red: "&4"
yellow: "&e"
green: "&a"
aqua: "&b"
blue: "&9"
purple: "&5"
pink: "&d"
```

When equipped, modify the player's chat message color.

Do not permanently change the player's name or prefix.

Make the chat integration compatible with normal Paper chat events and avoid breaking other chat plugins.

Provide a configurable option for enabling/disabling chat color modification.

---

### Chat Tags

Allow players to unlock and equip chat tags.

Examples:

```text
[VIP]
[MVP]
[LEGEND]
[PRO]
[OG]
[BUILDER]
```

The tag must be configurable.

Example:

```yaml
display: "&d[VIP]"
```

The plugin must allow PlaceholderAPI placeholders inside tag displays.

The tag should be inserted into chat without replacing LuckPerms prefixes unless configured to do so.

Provide a configurable chat format.

Example:

```yaml
chat-format: "{tag} {prefix}{player}&7: {message}"
```

---

# 2. PlayerPoints Economy

Use PlayerPoints as the main cosmetic currency.

PlayerPoints must be a soft dependency where possible, but the plugin should clearly warn in console if PlayerPoints is missing.

Configuration:

```yaml
economy:
  provider: PLAYERPOINTS
```

The system should be written using an economy abstraction so another economy provider can be added later.

For now implement:

* PlayerPoints
* Balance check
* Take points
* Give points
* Purchase
* Refund if needed

Example cosmetic:

```yaml
flame:
  display-name: "&cFlame"
  material: FLAME
  price: 500
  enabled: true
```

---

# 3. Cosmetic Ownership

Players must have:

* Owned cosmetics
* Equipped cosmetics
* Locked cosmetics

Players should NOT be charged again if they already own a cosmetic.

Buying a cosmetic should:

1. Check if enabled
2. Check if already owned
3. Check PlayerPoints balance
4. Remove the required points
5. Add ownership
6. Automatically equip it if configured
7. Send configurable message

---

# 4. Storage

Support:

### YAML

Default storage.

### SQLite

Optional.

### MySQL

Optional.

Configuration:

```yaml
storage:
  type: YAML
```

Supported:

```text
YAML
SQLITE
MYSQL
```

Create a clean storage interface so switching storage types does not require changing the rest of the plugin.

Do not store everything in memory permanently.

Cache player data properly and save it safely.

---

# 5. Menus

Create a complete configurable GUI system.

Main command:

```text
/cosmetics
```

Main menu:

```text
Particles
Arrow Effects
Death Effects
Kill Effects
Glow
Chat Colors
Tags
```

Each category must have its own menu.

Commands:

```text
/cosmetics
/cosmetics particles
/cosmetics arrows
/cosmetics death
/cosmetics kills
/cosmetics glow
/cosmetics colors
/cosmetics tags
```

The category commands must directly open their category menu without opening the main menu first.

---

# 6. Fully Configurable Menus

Do NOT hardcode menu layouts.

Menus must be stored in:

```text
menus/
```

Example:

```text
menus/
  main.yml
  particles.yml
  arrows.yml
  death-effects.yml
  kill-effects.yml
  glow.yml
  chat-colors.yml
  tags.yml
```

Allow configuration of:

* Menu title
* Size
* Item slots
* Materials
* Display names
* Lore
* CustomModelData
* Enchant glow
* Click actions
* Back button
* Close button
* Previous page
* Next page
* Background items

---

# 7. Adding New Cosmetics

This is extremely important.

The architecture must make it easy to add new cosmetics.

I want to be able to add a new cosmetic like:

```yaml
heart:
  display-name: "&dHeart"
  material: HEART
  price: 750
  enabled: true
```

without changing the main GUI code.

For particle cosmetics:

```yaml
heart:
  type: HEART
  amount: 5
  offset-x: 0.3
  offset-y: 0.5
  offset-z: 0.3
  speed: 0.01
```

For glow:

```yaml
purple:
  color: PURPLE
  price: 1000
```

For chat colors:

```yaml
pink:
  color: "&d"
  price: 500
```

For tags:

```yaml
vip:
  display: "&d[VIP]"
  price: 1000
```

For kill/death effects, use a configurable effect type system.

The code must have a proper registry/factory architecture so new effect implementations can be added cleanly.

---

# 8. Commands

Player commands:

```text
/cosmetics
/cosmetics particles
/cosmetics arrows
/cosmetics death
/cosmetics kills
/cosmetics glow
/cosmetics colors
/cosmetics tags
/cosmetics equip  
/cosmetics unequip 
/cosmetics owned
```

Admin commands:

```text
/cosmeticsadmin reload
/cosmeticsadmin give   
/cosmeticsadmin remove   
/cosmeticsadmin reset 
/cosmeticsadmin balance 
```

Permissions:

```text
mcosmetics.player
mcosmetics.admin
mcosmetics.admin.reload
mcosmetics.admin.give
mcosmetics.admin.remove
mcosmetics.admin.reset
```

---

# 9. Placeholders

Add PlaceholderAPI support.

Create placeholders such as:

```text
%mcosmetics_points%
%mcosmetics_equipped_particles%
%mcosmetics_equipped_arrow%
%mcosmetics_equipped_death%
%mcosmetics_equipped_kill%
%mcosmetics_equipped_glow%
%mcosmetics_equipped_chatcolor%
%mcosmetics_equipped_tag%
```

Also support placeholders such as:

```text
%player_name%
%luckperms_prefix%
```

where PlaceholderAPI provides them.

---

# 10. Messages

Do not hardcode player-facing messages.

Create:

```text
messages.yml
```

Include messages for:

* Purchase successful
* Not enough PlayerPoints
* Already owned
* Equipped
* Unequipped
* Invalid cosmetic
* Invalid category
* No permission
* Player not found
* Reload successful
* Admin actions

Support:

* Hex colors
* Legacy colors
* PlaceholderAPI
* Prefix

Example:

```yaml
prefix: "&d&lCosmetics &8ยป "

purchase-success: "{prefix}&fYou purchased &d{cosmetic}&f for &e{price} Points&f."
not-enough-points: "{prefix}&cYou don't have enough Points."
already-owned: "{prefix}&eYou already own this cosmetic."
equipped: "{prefix}&aYou equipped &f{cosmetic}&a."
unequipped: "{prefix}&7You unequipped your cosmetic."
```

---

# 11. Sounds

Every GUI action should support configurable sounds.

Example:

```yaml
sounds:
  click: UI_BUTTON_CLICK
  purchase: ENTITY_PLAYER_LEVELUP
  equip: BLOCK_NOTE_BLOCK_PLING
  error: ENTITY_VILLAGER_NO
```

Allow sounds to be disabled.

---

# 12. GUI Behavior

Show different lore depending on the player's state.

Locked:

```text
&cLocked

&7Price: &e500 Points

&fClick to purchase.
```

Owned:

```text
&aOwned

&fClick to equip.
```

Equipped:

```text
&dEquipped

&7Click to unequip.
```

The GUI must update immediately after:

* Purchase
* Equip
* Unequip
* Admin give
* Admin remove

---

# 13. Pagination

Every cosmetic category must support pagination.

Configurable:

```yaml
pagination:
  enabled: true
  previous-slot: 45
  next-slot: 53
```

Do not hardcode the number of cosmetics per page.

---

# 14. Reload System

Implement:

```text
/cosmeticsadmin reload
```

Reload:

* config.yml
* messages.yml
* cosmetic files
* menu files
* sounds
* prices
* GUI configuration

Do not require server restart for configuration changes where safely possible.

---

# 15. File Structure

Use a clean structure similar to:

```text
mCosmetics/
โ”œโ”€โ”€ pom.xml
โ”œโ”€โ”€ src/main/java/
โ”‚   โ””โ”€โ”€ me/moody/mcosmetics/
โ”‚       โ”œโ”€โ”€ MCosmetics.java
โ”‚       โ”œโ”€โ”€ command/
โ”‚       โ”œโ”€โ”€ config/
โ”‚       โ”œโ”€โ”€ cosmetics/
โ”‚       โ”‚   โ”œโ”€โ”€ Cosmetic.java
โ”‚       โ”‚   โ”œโ”€โ”€ CosmeticType.java
โ”‚       โ”‚   โ”œโ”€โ”€ CosmeticManager.java
โ”‚       โ”‚   โ”œโ”€โ”€ particle/
โ”‚       โ”‚   โ”œโ”€โ”€ arrow/
โ”‚       โ”‚   โ”œโ”€โ”€ death/
โ”‚       โ”‚   โ”œโ”€โ”€ kill/
โ”‚       โ”‚   โ”œโ”€โ”€ glow/
โ”‚       โ”‚   โ”œโ”€โ”€ chatcolor/
โ”‚       โ”‚   โ””โ”€โ”€ tag/
โ”‚       โ”œโ”€โ”€ economy/
โ”‚       โ”œโ”€โ”€ storage/
โ”‚       โ”œโ”€โ”€ gui/
โ”‚       โ”œโ”€โ”€ listener/
โ”‚       โ”œโ”€โ”€ placeholder/
โ”‚       โ””โ”€โ”€ util/
โ”‚
โ””โ”€โ”€ src/main/resources/
    โ”œโ”€โ”€ plugin.yml
    โ”œโ”€โ”€ config.yml
    โ”œโ”€โ”€ messages.yml
    โ”œโ”€โ”€ cosmetics/
    โ”‚   โ”œโ”€โ”€ particles.yml
    โ”‚   โ”œโ”€โ”€ arrows.yml
    โ”‚   โ”œโ”€โ”€ death-effects.yml
    โ”‚   โ”œโ”€โ”€ kill-effects.yml
    โ”‚   โ”œโ”€โ”€ glow.yml
    โ”‚   โ”œโ”€โ”€ chat-colors.yml
    โ”‚   โ””โ”€โ”€ tags.yml
    โ””โ”€โ”€ menus/
        โ”œโ”€โ”€ main.yml
        โ”œโ”€โ”€ particles.yml
        โ”œโ”€โ”€ arrows.yml
        โ”œโ”€โ”€ death-effects.yml
        โ”œโ”€โ”€ kill-effects.yml
        โ”œโ”€โ”€ glow.yml
        โ”œโ”€โ”€ chat-colors.yml
        โ””โ”€โ”€ tags.yml
```

You may improve this architecture if you have a better clean design.

---

# 16. Performance

The plugin must be optimized for a real production server.

Important:

* Do not run unnecessary tasks every tick for every player.
* Only run particle tasks for players who have an equipped particle.
* Stop cosmetic tasks when players leave.
* Clean up all Bukkit tasks.
* Avoid memory leaks.
* Avoid synchronous database queries during gameplay.
* Cache player cosmetic data.
* Use async operations for MySQL/SQLite where appropriate.
* Do not create thousands of Bukkit tasks unnecessarily.
* Use a centralized scheduler where possible.

---

# 17. Compatibility

Target:

```text
Paper 1.21.11
Java 21
```

Do not use unnecessary version-specific NMS.

Use Bukkit/Paper APIs whenever possible.

The plugin should coexist with:

* LuckPerms
* PlaceholderAPI
* TAB
* Essentials/CMI
* WorldGuard
* PlayerPoints
* other chat plugins

Do not overwrite unrelated scoreboard teams.

Do not break player prefixes.

Do not break existing chat formatting unless the player has an mCosmetics chat color/tag equipped.

---

# 18. plugin.yml

Use:

```yaml
name: mCosmetics
version: 1.0.0
main: me.moody.mcosmetics.MCosmetics
api-version: '1.21'
author: Moody - _Yasta
softdepend:
  - PlaceholderAPI
  - PlayerPoints
```

Add all commands and permissions properly.

---

# 19. Default Cosmetics

The first generated version must include multiple working examples in every category.

Particles:

* Flame
* Heart
* Cloud
* Enchant
* End Rod
* Soul Fire Flame
* Totem

Arrow Effects:

* Flame
* Heart
* Crit
* Smoke
* End Rod

Death Effects:

* Lightning
* Heart Explosion
* Soul Burst
* Fire Burst
* Totem Burst

Kill Effects:

* Lightning
* Flame Burst
* Heart Burst
* Soul Burst
* Totem Burst

Glow:

* White
* Red
* Orange
* Yellow
* Green
* Aqua
* Blue
* Purple
* Pink

Chat Colors:

* White
* Gray
* Red
* Orange
* Yellow
* Green
* Aqua
* Blue
* Purple
* Pink

Tags:

* VIP
* MVP
* LEGEND
* PRO
* OG

Give every default cosmetic a configurable PlayerPoints price.

---

# 20. Important Architecture Requirement

Do NOT make every cosmetic a hardcoded Java class.

I want the plugin to be data-driven as much as reasonably possible.

The core plugin should understand:

```text
Cosmetic Type
Cosmetic ID
Display Name
Material
Price
Permission
Enabled
Configuration
```

Then each cosmetic type has its own renderer/handler.

For example:

```text
ParticleCosmeticHandler
ArrowCosmeticHandler
DeathEffectHandler
KillEffectHandler
GlowHandler
ChatColorHandler
TagHandler
```

This makes it possible to add more cosmetic IDs without rewriting the core system.

---

# 21. Final Requirements

Before finishing:

1. Make sure the project compiles with Maven.
2. Make sure there are no missing imports.
3. Make sure plugin.yml matches the main class.
4. Make sure all default YAML files are valid.
5. Make sure all commands work.
6. Make sure PlayerPoints integration works.
7. Make sure ownership is persistent.
8. Make sure GUI pagination works.
9. Make sure all seven cosmetic categories work.
10. Make sure reload works.
11. Make sure PlaceholderAPI expansion works.
12. Make sure the plugin does not throw errors when PlaceholderAPI is absent.
13. Make sure the plugin does not crash when PlayerPoints is absent; instead disable purchasing and show a clear console warning.
14. Make sure player data is safely saved when the player quits and when the server shuts down.
15. Make sure all Bukkit tasks are cancelled correctly.
16. Make sure the code is clean, maintainable, and actually production-ready.

## Output Requirements

Do NOT give me a high-level explanation only.

Actually create the complete Maven project.

Give me every required source file and resource file.

The result must be directly buildable with:

```text
mvn clean package
```

Do not leave TODOs, placeholders, pseudocode, or "implement this later".

Every class and file required for the plugin to work must be fully implemented.

At the end, provide:

1. Complete project tree
2. All source files
3. All YAML files
4. pom.xml
5. plugin.yml
6. Build command
7. Installation instructions
8. Example instructions for adding a completely new cosmetic to each of the seven categories

The plugin must be named `mCosmetics` and the author must be `Moody - _Yasta`.
Kodari AI
KodariSep 10 at 9:19 pm 3
MCosmeticsSuite
A data-driven cosmetics plugin for Paper 1.21.11 with seven cosmetic categories: particles, arrow effects, death effects, kill effects, glow colors, chat colors, and chat tags. Features a fully configurable GUI system with pagination, PlayerPoints economy integration, YAML/SQLite/MySQL storage abstraction, PlaceholderAPI support, and a registry-based architecture allowing new cosmetics to be added via YAML configuration without code changes. Includes admin commands, reload system, configurable sounds, and safe scoreboard team handling for glow effects.

Iโ€™ll create the Maven project in dependency order: core/configuration and storage, cosmetics/economy services, GUI and listeners, commands/placeholders, then all default resources and build metadata.

Created the complete mCosmetics Maven project for Paper 1.21.11 / Java 21.

Project tree

Plain Text
mCosmetics/
โ”œโ”€โ”€ pom.xml
โ””โ”€โ”€ src/main/
    โ”œโ”€โ”€ java/me/moody/mcosmetics/
    โ”‚   โ”œโ”€โ”€ MCosmetics.java
    โ”‚   โ”œโ”€โ”€ Cosmetic.java
    โ”‚   โ”œโ”€โ”€ CosmeticActions.java
    โ”‚   โ”œโ”€โ”€ CosmeticType.java
    โ”‚   โ”œโ”€โ”€ PlayerData.java
    โ”‚   โ”œโ”€โ”€ command/
    โ”‚   โ”‚   โ”œโ”€โ”€ AdminCommand.java
    โ”‚   โ”‚   โ””โ”€โ”€ CosmeticsCommand.java
    โ”‚   โ”œโ”€โ”€ config/
    โ”‚   โ”‚   โ””โ”€โ”€ ConfigManager.java
    โ”‚   โ”œโ”€โ”€ cosmetics/
    โ”‚   โ”‚   โ””โ”€โ”€ CosmeticManager.java
    โ”‚   โ”œโ”€โ”€ economy/
    โ”‚   โ”‚   โ”œโ”€โ”€ EconomyProvider.java
    โ”‚   โ”‚   โ””โ”€โ”€ PlayerPointsEconomy.java
    โ”‚   โ”œโ”€โ”€ effects/
    โ”‚   โ”‚   โ””โ”€โ”€ EffectService.java
    โ”‚   โ”œโ”€โ”€ gui/
    โ”‚   โ”‚   โ”œโ”€โ”€ CosmeticMenu.java
    โ”‚   โ”‚   โ””โ”€โ”€ MenuHolder.java
    โ”‚   โ”œโ”€โ”€ listener/
    โ”‚   โ”‚   โ”œโ”€โ”€ ChatListener.java
    โ”‚   โ”‚   โ””โ”€โ”€ CosmeticListener.java
    โ”‚   โ”œโ”€โ”€ placeholder/
    โ”‚   โ”‚   โ””โ”€โ”€ CosmeticsExpansion.java
    โ”‚   โ”œโ”€โ”€ storage/
    โ”‚   โ”‚   โ”œโ”€โ”€ SqlStorage.java
    โ”‚   โ”‚   โ”œโ”€โ”€ Storage.java
    โ”‚   โ”‚   โ””โ”€โ”€ YamlStorage.java
    โ”‚   โ””โ”€โ”€ util/
    โ”‚       โ”œโ”€โ”€ PlaceholderSupport.java
    โ”‚       โ””โ”€โ”€ TextUtil.java
    โ””โ”€โ”€ resources/
        โ”œโ”€โ”€ plugin.yml
        โ”œโ”€โ”€ config.yml
        โ”œโ”€โ”€ messages.yml
        โ”œโ”€โ”€ cosmetics/
        โ”‚   โ”œโ”€โ”€ particles.yml
        โ”‚   โ”œโ”€โ”€ arrows.yml
        โ”‚   โ”œโ”€โ”€ death-effects.yml
        โ”‚   โ”œโ”€โ”€ kill-effects.yml
        โ”‚   โ”œโ”€โ”€ glow.yml
        โ”‚   โ”œโ”€โ”€ chat-colors.yml
        โ”‚   โ””โ”€โ”€ tags.yml
        โ””โ”€โ”€ menus/
            โ”œโ”€โ”€ main.yml
            โ”œโ”€โ”€ particles.yml
            โ”œโ”€โ”€ arrows.yml
            โ”œโ”€โ”€ death-effects.yml
            โ”œโ”€โ”€ kill-effects.yml
            โ”œโ”€โ”€ glow.yml
            โ”œโ”€โ”€ chat-colors.yml
            โ””โ”€โ”€ tags.yml

Included functionality

  • Seven configurable cosmetic categories

  • YAML, SQLite, and MySQL storage

  • PlayerPoints integration through a soft reflection-based adapter

  • Ownership and equipped cosmetic tracking

  • Configurable paginated GUI menus

  • Purchase, equip, unequip, admin give/remove/reset

  • Particle and projectile effects

  • Kill and death effects

  • Safe plugin-managed glow teams

  • Chat colors and configurable tags

  • PlaceholderAPI expansion

  • Reload command

  • Configurable messages, materials, lore, sounds, menus, prices, and permissions

  • Paper library declarations for SQLite and MySQL drivers

  • Default examples for every category

Build

Shell
mvn clean package

The resulting plugin jar is:

Plain Text
target/mCosmetics-1.0.0.jar

Installation

  1. Build the project with Maven.

  2. Copy the generated jar into the serverโ€™s plugins folder.

  3. Install PlayerPoints if purchasing should be enabled.

  4. Install PlaceholderAPI for external placeholders such as LuckPerms prefixes.

  5. Start the server.

  6. Edit files under plugins/mCosmetics/.

  7. Run:

Plain Text
/cosmeticsadmin reload

Adding new cosmetics

Particle

Add to cosmetics/particles.yml:

YAML
rainbow:
  display-name: "&dRainbow"
  material: AMETHYST_SHARD
  price: 900
  enabled: true
  particle: END_ROD
  amount: 8
  offset-x: 0.4
  offset-y: 0.6
  offset-z: 0.4
  speed: 0.02

Arrow effect

Add to cosmetics/arrows.yml:

YAML
soul:
  display-name: "&bSoul Arrows"
  material: SOUL_TORCH
  price: 800
  enabled: true
  particle: SOUL_FIRE_FLAME
  amount: 4

Death effect

Add to cosmetics/death-effects.yml:

YAML
portal-burst:
  display-name: "&5Portal Burst"
  material: OBSIDIAN
  price: 1000
  enabled: true
  effect: PORTAL
  particle: PORTAL
  amount: 40

Kill effect

Add to cosmetics/kill-effects.yml:

YAML
ender-kill:
  display-name: "&5Ender Kill"
  material: ENDER_PEARL
  price: 1100
  enabled: true
  effect: ENDER
  particle: PORTAL
  amount: 45

Glow

Add to cosmetics/glow.yml:

YAML
cyan:
  display-name: "&bCyan Glow"
  material: CYAN_DYE
  price: 750
  enabled: true
  color: AQUA

Chat color

Add to cosmetics/chat-colors.yml:

YAML
gold:
  display-name: "&6Gold"
  material: GOLD_NUGGET
  price: 500
  enabled: true
  color: "&6"

Chat tag

Add to cosmetics/tags.yml:

YAML
creator:
  display-name: "&dCreator"
  material: NAME_TAG
  price: 1500
  enabled: true
  display: "&d[CREATOR]"

New cosmetics become available after:

Plain Text
/cosmeticsadmin reload
Kodari can make mistakes. Review important code before using.
Files
src
pom.xml
Code
41 1,587
src/main/java/me/moody/mcosmetics/MCosmetics.java
package me.moody.mcosmetics;

import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.moody.mcosmetics.command.AdminCommand;
import me.moody.mcosmetics.command.CosmeticsCommand;
import me.moody.mcosmetics.config.ConfigManager;
import me.moody.mcosmetics.cosmetics.CosmeticManager;
import me.moody.mcosmetics.effects.EffectService;
import me.moody.mcosmetics.economy.EconomyProvider;
import me.moody.mcosmetics.economy.PlayerPointsEconomy;
import me.moody.mcosmetics.gui.CosmeticMenu;
import me.moody.mcosmetics.listener.CosmeticListener;
import me.moody.mcosmetics.listener.ChatListener;
import me.moody.mcosmetics.placeholder.CosmeticsExpansion;
import me.moody.mcosmetics.storage.SqlStorage;
import me.moody.mcosmetics.storage.Storage;
import me.moody.mcosmetics.storage.YamlStorage;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.UUID;

public final class MCosmetics extends JavaPlugin {
    private ConfigManager config;
    private CosmeticManager cosmetics;
    private Storage storage;
    private EconomyProvider economy;
    private CosmeticActions actions;
    private EffectService effects;
    private final Map<UUID, PlayerData> data = new ConcurrentHashMap<>();

    @Override
    public void onEnable() {
        saveDefaultConfig();
        saveResource("messages.yml", false);
        for (String file : new String[]{"particles", "arrows", "death-effects", "kill-effects", "glow", "chat-colors", "tags"}) saveResource("cosmetics/" + file + ".yml", false);
        for (String file : new String[]{"main", "particles", "arrows", "death-effects", "kill-effects", "glow", "chat-colors", "tags"}) saveResource("menus/" + file + ".yml", false);
        config = new ConfigManager(this);
        cosmetics = new CosmeticManager(this);
        storage = createStorage();
        economy = new PlayerPointsEconomy();
        if (!economy.isAvailable()) getLogger().warning("PlayerPoints is missing or unavailable; cosmetic purchases are disabled.");
        actions = new CosmeticActions(this, cosmetics, economy);
        effects = new EffectService(this);
        effects.start();
        Bukkit.getPluginManager().registerEvents(new CosmeticListener(this), this);
        Bukkit.getPluginManager().registerEvents(new ChatListener(this), this);
        getCommand("cosmetics").setExecutor(new CosmeticsCommand(this));
        getCommand("cosmetics").setTabCompleter(new CosmeticsCommand(this));
        getCommand("cosmeticsadmin").setExecutor(new AdminCommand(this));
        getCommand("cosmeticsadmin").setTabCompleter(new AdminCommand(this));
        if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) new CosmeticsExpansion(this).register();
    }

    private Storage createStorage() {
        String type = config.config().getString("storage.type", "YAML");
        if (type.equalsIgnoreCase("YAML")) return new YamlStorage(this);
        try { return new SqlStorage(this, type); }
        catch (SQLException exception) {
            getLogger().warning("Could not initialize " + type + " storage: " + exception.getMessage() + ". Falling back to YAML.");
            return new YamlStorage(this);
        }
    }

    @Override
    public void onDisable() {
        for (UUID uuid : data.keySet()) storage.save(uuid, data.get(uuid));
        if (effects != null) effects.stop();
        if (storage != null) storage.close();
    }

    public void load(Player player) { data.put(player.getUniqueId(), storage.load(player.getUniqueId())); refreshVisuals(player); }
    public void unload(Player player) { PlayerData playerData = data.remove(player.getUniqueId()); if (playerData != null) storage.save(player.getUniqueId(), playerData); }
    public PlayerData data(Player player) { return data.computeIfAbsent(player.getUniqueId(), key -> storage.load(key)); }
    public void save(Player player) { storage.save(player.getUniqueId(), data(player)); }
    public void refreshVisuals(Player player) { if (effects != null) effects.updateGlow(player); }
    public void playSound(Player player, String key) {
        if (!config.config().getBoolean("sounds.enabled", true)) return;
        String name = config.config().getString("sounds." + key);
        if (name == null || name.isBlank()) return;
        try { player.playSound(player.getLocation(), Sound.valueOf(name.toUpperCase()), 1.0f, 1.0f); }
        catch (IllegalArgumentException ignored) { }
    }
    public void reloadEverything() { config.reload(); cosmetics.reload(); }
    public void openMenu(Player player, CosmeticType type, int page) { CosmeticMenu.open(this, player, type, page); }
    public ConfigManager config() { return config; }
    public CosmeticManager cosmetics() { return cosmetics; }
    public CosmeticActions actions() { return actions; }
    public EconomyProvider economy() { return economy; }
    public EffectService effects() { return effects; }
}