woaiini_
๐Ÿ“Ž 1 file 19,852 chars
๐Ÿ“„
pasted-code-1794708965601.txt
txt 606 lines
โ–ถ
# Gstaff - Advanced Minecraft Staff Management Plugin

I want you to develop a professional, fully customizable Minecraft staff management plugin called **Gstaff**.

The goal is to create an all-in-one staff plugin with a staff activity logging and reward system, punishment management, warnings, and an advanced vanish system.

I don't want a basic plugin with limited features. I want something polished, reliable, optimized, and highly configurable, with the functionality and attention to detail of established premium plugins like LiteBans.

**IMPORTANT:** Read and understand every requirement before starting development. Do not skip features, leave unfinished systems, or replace requested functionality with basic alternatives. Make sure every feature actually works and that all systems integrate properly.

---

# 1. STAFF LOGGING SYSTEM - /log

This is one of the most important features of Gstaff.

I want a staff activity logging system where staff members can submit their duty logs and receive randomized rewards after successfully completing their log.

### Command
- `/log` - Opens the staff logging dialog.

### Dialog GUI

When a staff member executes `/log`, open a modern, clean, and professional dialog GUI.

The dialog should have the following:

**1. GTag / Staff Tag**
- A text input where the staff member enters their GTag or staff identification tag.
- Make the label and description configurable.

**2. On-Duty Time**
- Another text input where staff members can enter their duty time.
- Example: `7 PM - 10 PM`.
- Allow them to enter their own format instead of forcing a specific time format.

**3. Confirmation Buttons**
- Confirm: Submits their staff log.
- Cancel: Closes the dialog without submitting anything.

Make the dialog visually clean and organized. Use proper spacing, titles, descriptions, input labels, and button colors.

Use the native Minecraft Dialog API if it is supported by the target server version. If it isn't supported, implement a polished inventory GUI fallback. Do not remove the input fields or functionality.

### Staff Log Records

Every successful submission should be saved permanently.

Store:
- Staff member's UUID and username.
- GTag.
- Submitted duty time.
- Date and exact submission timestamp.
- Assigned LuckPerms group.
- Reward received.
- Current streak.

Make sure logs are persistent even after server restarts.

Add protection against duplicate submissions and configurable cooldowns or daily submission limits to prevent reward farming.

### Randomized Reward System

After a successful log submission, automatically give the staff member a randomized reward.

Possible rewards include:
- Money.
- Crate keys.
- Cosmetics.
- Custom items.
- Other configurable rewards.
- Custom console commands.

I want the rewards to be fully customizable through `log.yml`.

Examples:
- Money: Give the staff member $5,000.
- Keys: Give them 1 crate key.
- Cosmetics: Give them a cosmetic reward.
- Custom: Execute a configured command as console.

Support integrations such as Vault for economy and configurable console commands for external crate, cosmetic, and item plugins.

### Streak System

Implement a proper consecutive-day logging streak system.

The more consecutive days a staff member submits their log, the better their possible rewards should become.

For example:
- 1-day streak: Basic rewards.
- 3-day streak: Better rewards.
- 7-day streak: Higher-value rewards.
- 14-day streak: Premium rewards.
- 30-day streak: Exclusive rewards.

These are examples. I want to customize the streak milestones, reward pools, probabilities, and amounts.

Make sure missed days correctly reset or affect streaks according to configurable rules.

### LuckPerms Rank-Based Rewards

This is very important.

The reward system must recognize the staff member's LuckPerms group.

Higher staff ranks should have better reward chances and access to better reward pools.

For example:
- Trial Moderator: Basic reward pool.
- Moderator: Improved reward chances.
- Senior Moderator: Better reward pool.
- Administrator: Higher-value rewards.
- Head Administrator: Premium reward pool.

These are only examples. Do not hardcode these ranks.

I want to configure:
- Which LuckPerms groups have access to specific reward pools.
- Reward probabilities.
- Reward amounts.
- Reward rarity.
- Streak multipliers.
- Rank-based reward chances.
- Special rewards for specific groups.

Use LuckPerms group information and group weights or an explicitly configurable priority system to determine the appropriate staff rank. Handle group inheritance correctly.

**Important:** Higher ranks and longer streaks should improve reward opportunities, but the entire reward system must remain configurable. Do not hardcode reward values or chances.

---

# 2. PUNISHMENT SYSTEM

Create a complete punishment management system inspired by the functionality of LiteBans.

I want the punishment system to be independent, reliable, and fully customizable.

### Required Commands

**Ban**
- `/ban  `
- Permanently bans a player.
- Prevents them from joining the server.

**Temporary Ban**
- `/tempban   `
- Bans a player for a specified amount of time.
- Automatically expires when the duration ends.

**Kick**
- `/kick  `
- Immediately disconnects the player from the server.

**Temporary Kick**
- `/tempkick   `
- Immediately kicks the player.
- Prevents them from rejoining until the configured expiration time.

**Mute**
- `/mute  `
- Prevents a player from communicating through supported chat and voice systems.

**Temporary Mute**
- `/tempmute   `
- Temporarily mutes the player.
- Automatically removes the mute when the duration expires.

Also implement the necessary management commands:
- `/unban `
- `/unmute `
- `/banlist`
- `/history `

Add tab completion for commands wherever applicable.

### LiteBans-Like Customization

I want the punishment system to have the same general level of customization and convenience as LiteBans.

Everything should be configurable, including:
- Punishment messages.
- Reasons.
- Default reasons.
- Duration formats.
- Broadcast messages.
- Silent punishments.
- Permission exemptions.
- Bypass permissions.
- Punishment expiration.
- Offline player punishments.
- Staff notifications.
- Punishment history.
- Date and time formatting.
- Command aliases.
- Custom placeholders.

Use UUIDs rather than relying exclusively on usernames.

Each punishment should have a unique case ID and a record containing the staff member, punished player, reason, punishment type, and timestamp.

Make sure expired punishments are handled correctly and cannot accidentally remain active.

### Voice Chat and Text Chat Muting

I specifically want `/mute` and `/tempmute` to mute both:

1. Normal Minecraft text chat.
2. Simple Voice Chat.

For text chat:
- Prevent muted players from sending messages.
- Display a configurable muted notification.
- Optionally prevent access to configurable chat-related commands.

For Simple Voice Chat:
- Integrate with the Simple Voice Chat API or its supported integration methods.
- Actually prevent muted players from transmitting voice.
- Automatically restore their voice chat access after their mute expires or they are unmuted.

**Important:** Do not assume LuckPerms alone can mute Simple Voice Chat. LuckPerms should handle permissions, while Gstaff must use the appropriate voice chat integration to enforce voice mutes.

If Simple Voice Chat isn't installed, gracefully disable voice-specific functionality without breaking the rest of the plugin.

---

# 3. WARNING SYSTEM - /warn

Create a complete warning system.

### Commands

- `/warn  ` - Gives a player a warning.
- `/warns` - Allows a player to view their own warnings.
- `/warns ` - Allows authorized staff to view another player's warnings.
- `/unwarn  ` - Removes a specific warning.
- `/clearwarns ` - Clears a player's warnings.

### Warning Records

Every warning must be saved permanently.

Store:
- Player UUID.
- Player username.
- Staff member who issued the warning.
- Warning reason.
- Date and timestamp.
- Unique warning ID.

### Automatic Punishment

Every player is allowed a maximum of **3 active warnings**.

When a player receives their third warning:
- Automatically issue a 1-day ban.
- Record the automatic ban in their punishment history.
- Show the player a configurable message explaining that they reached the warning limit.
- Notify staff members.

The default threshold should be 3 warnings, and the default automatic ban duration should be 24 hours.

Make both configurable through `warn.yml`.

Make sure the third warning is properly recorded before the automatic ban is applied.

---

# 4. ADVANCED VANISH SYSTEM - /vanish

I want Gstaff to have a highly advanced vanish system.

This shouldn't be a basic vanish command. I want the system to include features that make staff moderation completely discreet.

### Main Command
- `/vanish` - Toggles vanish on or off.
- `/vanish on` - Enables vanish.
- `/vanish off` - Disables vanish.

### Fake Join and Leave Messages

When a staff member enables vanish:
- Hide them from normal players.
- Make it appear as though they left the server.
- Send a configurable fake leave message.

When they disable vanish:
- Make it appear as though they joined the server.
- Send a configurable fake join message.

The messages must be customizable. I specifically want to be able to change the fake join and leave message templates through `config.yml`, with the language files also providing the default message templates.

Do not broadcast actual server quit or join messages when staff members toggle vanish.

### Advanced Vanish Features

Implement the following:

**Player Visibility**
- Hidden players must not see vanished staff members.
- Vanished staff should not appear in normal players' tab lists.
- Staff members with the appropriate permission can see other vanished staff.
- Prevent hidden staff from appearing in normal player visibility checks.

**Silent Container Access**
- Vanished staff should be able to open chests, barrels, shulker boxes, and other containers without revealing that they opened them.
- Prevent visible chest opening animations where possible.
- Prevent chest opening sounds from being broadcast to other players.
- Do not reveal container interaction through other player-visible effects.
- Ensure staff can still interact with containers normally.

**Silent Moderation**
- Hide appropriate interaction notifications.
- Prevent accidental visibility through configurable staff actions.
- Avoid unnecessary chat announcements.
- Make staff moderation discreet.

**Additional Features**
- Configurable item pickup while vanished.
- Configurable item dropping while vanished.
- Configurable damage immunity.
- Configurable flight while vanished.
- Configurable interaction restrictions.
- Configurable night vision.
- Configurable vanish persistence after reconnecting.
- Proper handling of world changes and teleports.
- Prevent vanished staff from being exposed through normal player listings or tab completion where applicable.

Use proper server API methods and packet-level handling only where necessary to achieve silent container interactions. Do not claim an interaction is silent if other players can still see its animation or hear its sound.

Make all these features individually configurable.

---

# 5. LUCKPERMS INTEGRATION AND PERMISSIONS

LuckPerms support is required.

I want Gstaff to automatically recognize staff ranks and use them for:
- Command permissions.
- Rank-based reward pools.
- Reward probabilities.
- Vanish visibility.
- Punishment permissions.
- Warning permissions.
- Staff log access.

Create organized permission nodes.

Examples:

`gstaff.log`
`gstaff.log.admin`
`gstaff.log.others`
`gstaff.ban`
`gstaff.tempban`
`gstaff.kick`
`gstaff.tempkick`
`gstaff.mute`
`gstaff.tempmute`
`gstaff.warn`
`gstaff.warns`
`gstaff.warns.others`
`gstaff.vanish`
`gstaff.vanish.see`
`gstaff.vanish.bypass`
`gstaff.bypass.mute`
`gstaff.bypass.ban`
`gstaff.reload`

These are examples. Include all required permission nodes for every command and feature.

Make sure permissions are checked server-side and cannot be bypassed through GUI interactions or command aliases.

---

# 6. HEX COLOR AND GRADIENT SUPPORT

I want complete modern color support.

Support:
- Legacy Minecraft color codes.
- Hexadecimal colors.
- RGB colors.
- MiniMessage formatting.
- Gradient colors.
- Custom formatting.

Examples:

`&#AA55FF`
`<#AA55FF>`
`Gstaff`

Make sure gradients and hex colors work in:
- Chat messages.
- Dialog GUIs.
- Inventory GUIs.
- Titles and subtitles.
- Action bars.
- Broadcast messages.
- Punishment messages.
- Staff notifications.
- Language files.

Use a consistent formatting system instead of implementing separate, incompatible color parsers for different features.

---

# 7. CONFIGURATION STRUCTURE

I want the configuration files organized and easy to maintain.

Do not create unnecessary configuration folders or put every setting into one enormous file.

Use the following structure:

```text
plugins/
โ””โ”€โ”€ Gstaff/
    โ”œโ”€โ”€ config.yml
    โ”œโ”€โ”€ log.yml
    โ”œโ”€โ”€ ban.yml
    โ”œโ”€โ”€ kick.yml
    โ”œโ”€โ”€ mute.yml
    โ”œโ”€โ”€ warn.yml
    โ”œโ”€โ”€ vanish.yml
    โ”œโ”€โ”€ language/
    โ”‚   โ””โ”€โ”€ en_US.yml
    โ”œโ”€โ”€ data/
    โ”‚   โ””โ”€โ”€ gstaff.db
    โ””โ”€โ”€ logs/
```

### config.yml

Keep this file for general settings:
- Plugin prefix.
- General plugin settings.
- Default language.
- General integrations.
- General formatting settings.
- Optional fake join and leave message overrides for vanish.
- Other essential global settings.

Keep it simple. Do not put every feature's configuration here.

### log.yml

Contains everything related to staff logging:
- Dialog settings.
- Input fields.
- Daily logging rules.
- Cooldowns.
- Streak system.
- Reward pools.
- Randomized reward chances.
- LuckPerms rank configurations.
- Rank-based reward probabilities.
- Reward amounts.
- Custom commands.
- Streak milestones.

### ban.yml

Contains permanent and temporary ban settings, including their messages, permissions, durations, exemptions, and broadcast options.

### kick.yml

Contains kick and temporary kick settings, messages, permissions, and other customization.

### mute.yml

Contains mute and temporary mute settings, text chat integration, Simple Voice Chat integration, durations, and messages.

### warn.yml

Contains warning limits, automatic punishment settings, expiration rules, messages, and warning options.

### vanish.yml

Contains vanish behavior, visibility, silent container interactions, pickup and drop settings, damage immunity, flight, night vision, persistence, and other vanish options.

### language/en_US.yml

Every text displayed to players or staff must be customizable here.

This includes:
- Prefix messages.
- Command usage.
- Permission errors.
- Success and failure messages.
- Punishment messages.
- Warning messages.
- Staff notifications.
- Dialog titles and descriptions.
- Dialog input labels.
- Confirm and cancel buttons.
- Reward notifications.
- Streak messages.
- Vanish notifications.
- Fake join and leave message defaults.
- Chat mute notifications.
- Voice mute notifications.
- All GUI titles and item descriptions.

Do not hardcode player-facing messages in Java classes.

Make sure the plugin can safely generate default configuration files on its first startup and does not overwrite existing configurations during updates.

---

# 8. QUALITY, PERFORMANCE, AND DEVELOPMENT REQUIREMENTS

I want this plugin to be production-ready.

Follow these requirements:

**Compatibility**
- Target the specified Paper server version and use the appropriate server API.
- Use modern Java practices.
- Integrate with LuckPerms properly.
- Support Vault where needed.
- Support PlaceholderAPI optionally.
- Support Simple Voice Chat through its API when installed.
- Make external integrations optional where appropriate.

**Performance**
- Avoid unnecessary repeating tasks.
- Do not block the main server thread with database operations.
- Use efficient database queries.
- Avoid memory leaks.
- Properly manage listeners, scheduled tasks, and cached player data.
- Make sure all persistent information survives restarts.

**Data Management**
- Use a reliable persistent storage system, preferably SQLite by default.
- Use UUIDs for player identification.
- Save punishments, warnings, log submissions, streaks, and other important information.
- Handle concurrent requests and duplicate submissions safely.
- Make expiration handling reliable.

**Code Quality**
- Use a clean, modular package structure.
- Separate logging, rewards, punishments, warnings, vanish, permissions, storage, and configuration into their own managers or services.
- Avoid putting the entire plugin into one Java class.
- Avoid unnecessary dependencies.
- Include proper error handling.
- Provide meaningful console logs.
- Never silently ignore important errors.

**Commands**
- Every command must have proper permission checks.
- Add tab completion.
- Handle invalid arguments.
- Handle offline players where supported.
- Provide configurable usage messages.
- Make sure all commands work independently and together.

**Developer Documentation**
Provide:
- Complete source code.
- `plugin.yml` or the appropriate plugin metadata.
- Maven or Gradle build configuration.
- Required dependency information.
- Permission documentation.
- Command documentation.
- Configuration examples.
- Installation instructions.
- A README explaining every feature.

---

# 9. FINAL CHECKLIST - DO NOT SKIP

Before considering Gstaff complete, verify that:

1. `/log` opens the correct dialog and accepts the GTag and on-duty time.
2. Confirm and cancel buttons work correctly.
3. Successful logs are saved permanently.
4. Random rewards are properly distributed.
5. Streaks correctly improve reward opportunities.
6. LuckPerms ranks affect the configured reward pools and probabilities.
7. Ban, tempban, kick, and tempkick work correctly.
8. Mute and tempmute work for both text chat and Simple Voice Chat when the integration is installed.
9. Punishments expire correctly.
10. Every punishment is recorded with its case ID.
11. `/warn` records warnings correctly.
12. `/warns` displays the correct warning records.
13. The third active warning automatically triggers the configured 1-day ban.
14. `/vanish` properly hides and reveals staff members.
15. Fake join and leave messages work correctly.
16. Staff can access containers silently without exposing their activity to other players.
17. LuckPerms permissions work correctly for every command.
18. Hexadecimal and gradient colors display properly.
19. All player-facing text can be customized through the language folder.
20. All requested configurations are separate and organized.
21. No important data disappears after restarting the server.
22. The plugin compiles successfully without errors.
23. No major features are left unfinished or replaced with fake implementations.

**MOST IMPORTANT:** Do not just generate code that looks correct. Actually implement the functionality, check API compatibility, compile the plugin, and fix errors before declaring it finished.

If a requested feature requires an external plugin or API, clearly identify that dependency and implement a proper optional integration. Never pretend a feature works when it doesn't.

I want Gstaff to feel like a complete premium staff management plugin, not a collection of basic commands. Prioritize reliability, clean configuration, customization, performance, and a professional user experience.
Kodari AI
KodariNov 15 at 2:45 am 22
Gstaff
A comprehensive staff management plugin featuring a duty logging system with randomized rewards, streak tracking, and LuckPerms rank-based reward pools. Includes a complete punishment system with bans, tempbans, kicks, mutes, and voice chat integration for Simple Voice Chat. Provides a warning system with automatic punishment thresholds, and an advanced vanish system with silent container access, fake join/leave messages, and full player visibility control. Features hex color and gradient support, organized configuration files, SQLite persistence, and optional Vault and PlaceholderAPI integrations.

Plan:

  1. Build the Paper plugin foundation with SQLite persistence, modular managers, permissions, and configurable language.

  2. Implement staff logs/rewards/streaks, punishments/warnings, voice mute integration, and vanish behavior.

  3. Add command metadata, feature-specific configs, Gradle setup, and the requested README.

The core systems are in place. Iโ€™m tightening the server-side checks for dialog submissions and validating configurable reward amounts before finalizing the setup.

Implemented Gstaff for Paper 1.21.7+ and Java 21. /log uses the native Paper Dialog API; submissions, streaks, rewards, punishments, and warnings are stored in SQLite, with database work off the main thread.

Punishments, warning-limit bans, mute enforcement, vanish behavior, permissions, messages, and feature-specific configs are included. Optional integrations are explicit: LuckPerms for rank and offline-permission checks, Vault for money rewards, Simple Voice Chat for microphone muting, and ProtocolLib for silent container packets. Without ProtocolLib, silent container interactions are disabled and logged rather than presented as working.

The README documents installation, commands, permissions, configuration, and integration requirements.

woaiini_
๐Ÿ“Ž 1 file 4,695 chars
๐Ÿ“„
pasted-code-1794708989393.txt
txt 173 lines
โ–ถ
### UPDATED CONFIGURATION STRUCTURE

I want the configuration files organized, simple, and easy to manage. Avoid creating unnecessary YAML files.

Use this exact structure:

```text
plugins/
โ””โ”€โ”€ Gstaff/
    โ”œโ”€โ”€ config.yml
    โ”œโ”€โ”€ log.yml
    โ”œโ”€โ”€ punishments.yml
    โ”œโ”€โ”€ language/
    โ”‚   โ””โ”€โ”€ en_US.yml
    โ”œโ”€โ”€ data/
    โ”‚   โ””โ”€โ”€ gstaff.db
    โ””โ”€โ”€ logs/
```

### 1. config.yml

This is the main configuration file.

It must contain:
- Plugin prefix.
- General plugin settings.
- Default language.
- General integrations.
- General formatting settings.
- LuckPerms settings.
- Vault settings.
- PlaceholderAPI settings.
- Simple Voice Chat integration settings.
- **ALL vanish system configurations.**

The vanish system must be configured directly inside `config.yml` under its own `vanish:` section.

For example, include settings for:
- Fake join and leave messages.
- Player visibility.
- Tab list visibility.
- Staff visibility permissions.
- Silent container interactions.
- Silent chest opening sounds and animations.
- Item pickup and dropping.
- Damage immunity.
- Flight.
- Night vision.
- Interaction restrictions.
- Vanish persistence after reconnecting.
- World changes and teleportation behavior.
- Other advanced vanish settings.

Do not create a separate `vanish.yml` file.

### 2. log.yml

This file contains EVERYTHING related to the staff logging and reward system.

Include:
- Dialog GUI settings.
- GTag input.
- On-duty time input.
- Confirm and cancel buttons.
- Logging cooldowns.
- Daily logging restrictions.
- Streak system.
- Streak milestones.
- Randomized reward pools.
- Money rewards.
- Crate key rewards.
- Cosmetic rewards.
- Custom item rewards.
- Custom command rewards.
- LuckPerms rank-based reward pools.
- Reward probabilities and multipliers.

All reward configurations must be customizable here.

### 3. punishments.yml

I want ALL punishment-related systems inside ONE configuration file.

Do not separate ban, kick, mute, and warn into individual YAML files.

Instead, organize them into separate sections within `punishments.yml`:

```yaml
ban:
  enabled: true
  # Permanent and temporary ban settings
  # Messages, durations, permissions, exemptions
  # Broadcasts, silent punishments, expiration

kick:
  enabled: true
  # Kick and temporary kick settings
  # Messages, permissions, reasons
  # Broadcasts and customization

mute:
  enabled: true
  # Permanent and temporary mute settings
  # Text chat muting
  # Simple Voice Chat integration
  # Durations, exemptions, messages

warn:
  enabled: true
  # Warning limits
  # Maximum warnings
  # Automatic punishment
  # Warning expiration
  # Warning messages
  # Staff notifications
```

Each section must have its own independent settings, messages, permissions, and customization options.

Include all the functionality previously specified for:
- `/ban`
- `/tempban`
- `/unban`
- `/kick`
- `/tempkick`
- `/mute`
- `/tempmute`
- `/unmute`
- `/banlist`
- `/history`
- `/warn`
- `/warns`
- `/unwarn`
- `/clearwarns`

The warning system must retain its default maximum of 3 active warnings before automatically issuing a 1-day ban. Both values must remain configurable.

**Important:** Combining these systems into one YAML file must not combine their actual code into one class or manager. Keep the Java implementation modular and organized.

### 4. language/en_US.yml

ALL player-facing messages and displayed text must be configurable here.

This includes:
- General plugin messages.
- Staff logging messages.
- Dialog titles, descriptions, and button labels.
- Reward notifications.
- Streak notifications.
- Ban and temporary ban messages.
- Kick and temporary kick messages.
- Mute and temporary mute messages.
- Warning notifications.
- Vanish messages.
- Fake join and leave message templates.
- Staff notifications.
- Permission errors.
- Command usage messages.
- GUI titles and descriptions.

Never hardcode messages directly in Java classes.

### CONFIGURATION REQUIREMENTS

- Generate all default YAML files automatically on first startup.
- Never overwrite existing configurations during plugin updates.
- Validate configuration values and handle missing or invalid settings safely.
- Keep the YAML files properly formatted and documented.
- Use clear section names and comments.
- Ensure every feature reads its settings from the correct configuration file.
- Make `/gstaff reload` reload all supported configurations safely without requiring a server restart.

**Final requirement:** The only configuration files should be `config.yml`, `log.yml`, `punishments.yml`, and the language files. Do not create separate `ban.yml`, `kick.yml`, `mute.yml`, `warn.yml`, or `vanish.yml` files.
Kodari AI
KodariNov 15 at 3:09 am 4
  1. Trace the existing config loading and references to the separate punishment/vanish files.

  2. Consolidate defaults and runtime lookups into config.yml, log.yml, and punishments.yml, keeping the managers modular.

  3. Update reload behavior and documentation; stop generating the retired YAML files.

Consolidated the generated configs to config.yml, log.yml, punishments.yml, and language files. Vanish settings now live under config.yml:vanish; punishment settings are grouped under independent ban, kick, mute, and warn sections. Runtime lookups, permissions, mute handling, and reload behavior now use the consolidated structure.

On upgrade, legacy punishment and vanish settings are migrated without overwriting existing values; old files are removed only after a successful migration. Updated the README and added fallback to bundled English for missing language keys.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
manifest.kod
README.md
settings.gradle
Code
30 4,319
src/main/java/com/kodari/gstaff/GstaffPlugin.java
package com.kodari.gstaff;

import com.kodari.gstaff.command.CommandRouter;
import com.kodari.gstaff.config.ConfigManager;
import com.kodari.gstaff.integration.EconomyProvider;
import com.kodari.gstaff.logging.LogService;
import com.kodari.gstaff.logging.RewardService;
import com.kodari.gstaff.listener.PlayerListener;
import com.kodari.gstaff.permission.PermissionService;
import com.kodari.gstaff.permission.RankResolver;
import com.kodari.gstaff.punishment.PunishmentManager;
import com.kodari.gstaff.storage.SqliteStore;
import com.kodari.gstaff.text.Messages;
import com.kodari.gstaff.vanish.VanishManager;
import com.kodari.gstaff.warnings.WarningService;
import org.bukkit.Bukkit;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;

import java.lang.reflect.Method;

public final class GstaffPlugin extends JavaPlugin {
    private ConfigManager configs;
    private Messages messages;
    private SqliteStore database;
    private PermissionService permissions;
    private PunishmentManager punishments;
    private WarningService warnings;
    private RewardService rewards;
    private LogService logService;
    private VanishManager vanishManager;
    private Object protocolLibHook;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        configs = new ConfigManager(this);
        messages = new Messages(this);
        database = new SqliteStore(this);
        permissions = new PermissionService();
        permissions.setRankResolver(loadLuckPerms());
        EconomyProvider economy = loadVaultEconomy();
        punishments = new PunishmentManager(this);
        warnings = new WarningService(this);
        rewards = new RewardService(this, economy);
        logService = new LogService(this, rewards);
        vanishManager = new VanishManager(this);

        registerCommands();
        getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
        setupVoiceChat();
        setupProtocolLib();
        restorePersistedVanish();

        database.ready().whenComplete((ignored, failure) -> {
            if (failure != null) {
                getLogger().severe("Gstaff SQLite storage failed to initialize: " + failure.getMessage());
            } else {
                getLogger().info("Gstaff SQLite storage is ready.");
            }
        });
        for (var player : Bukkit.getOnlinePlayers()) {
            vanishManager.onJoin(player);
            punishments.onJoin(player);
        }
    }

    @Override
    public void onDisable() {
        if (vanishManager != null) {
            vanishManager.shutdown();
        }
        if (protocolLibHook != null) {
            try {
                protocolLibHook.getClass().getMethod("unregister").invoke(protocolLibHook);
            } catch (ReflectiveOperationException | LinkageError exception) {
                getLogger().warning("Could not unregister the optional ProtocolLib listener: " + exception.getMessage());
            }
        }
        if (database != null) {
            database.close();
        }
    }

    public void reloadSettings() {
        configs.reload();
        messages.reload();
        rewards.reload();
        vanishManager.reloadSettings();
        vanishManager.refreshVisibility();
    }

    public ConfigManager getConfigs() {
        return configs;
    }

    public Messages getMessages() {
        return messages;
    }

    public SqliteStore getDatabase() {
        return database;
    }

    public PermissionService getPermissions() {
        return permissions;
    }

    public PunishmentManager getPunishments() {
        return punishments;
    }

    public WarningService getWarnings() {
        return warnings;
    }

    public RewardService getRewards() {
        return rewards;
    }

    public LogService getLogService() {
        return logService;
    }

    public VanishManager getVanishManager() {
        return vanishManager;
    }

    private void registerCommands() {
        CommandRouter router = new CommandRouter(this);
        for (String name : new String[]{"gstaff", "log", "ban", "tempban", "kick", "tempkick", "mute", "tempmute",
                "unban", "unmute", "banlist", "history", "warn", "warns", "unwarn", "clearwarns", "vanish"}) {
            PluginCommand command = getCommand(name);
            if (command == null) {
                throw new IllegalStateException("Command " + name + " is missing from plugin.yml");
            }
            command.setExecutor(router);
            command.setTabCompleter(router);
        }
    }

    private RankResolver loadLuckPerms() {
        if (!getConfig().getBoolean("integrations.luckperms", true)
                || !Bukkit.getPluginManager().isPluginEnabled("LuckPerms")) {
            getLogger().info("LuckPerms was not detected; configured log rank pools will use the default rank.");
            return null;
        }
        try {
            Object hook = Class.forName("com.kodari.gstaff.integration.LuckPermsHook").getConstructor().newInstance();
            getLogger().info("LuckPerms rank and offline permission integration enabled.");
            return (RankResolver) hook;
        } catch (ReflectiveOperationException | LinkageError exception) {
            getLogger().warning("LuckPerms was detected but its API could not be loaded: " + exception.getMessage());
            return null;
        }
    }

    private EconomyProvider loadVaultEconomy() {
        if (!getConfig().getBoolean("integrations.vault", true)
                || !Bukkit.getPluginManager().isPluginEnabled("Vault")) {
            getLogger().info("Vault economy rewards are unavailable; command-based rewards remain enabled.");
            return null;
        }
        try {
            Class<?> hook = Class.forName("com.kodari.gstaff.integration.VaultHook");
            Method create = hook.getMethod("create", GstaffPlugin.class);
            EconomyProvider provider = (EconomyProvider) create.invoke(null, this);
            if (provider == null) {
                getLogger().warning("Vault is installed, but no economy provider is registered.");
            } else {
                getLogger().info("Vault economy rewards enabled.");
            }
            return provider;
        } catch (ReflectiveOperationException | LinkageError exception) {
            getLogger().warning("Vault was detected but its economy API could not be loaded: " + exception.getMessage());
            return null;
        }
    }

    private void setupVoiceChat() {
        if (!getConfig().getBoolean("integrations.simple-voice-chat", true)) {
            return;
        }
        if (!Bukkit.getPluginManager().isPluginEnabled("voicechat")) {
            getLogger().info("Simple Voice Chat was not detected; voice mute integration is inactive.");
            return;
        }
        try {
            Class<?> hookClass = Class.forName("com.kodari.gstaff.integration.VoicechatHook");
            Object hook = hookClass.getConstructor(GstaffPlugin.class).newInstance(this);
            boolean registered = (boolean) hookClass.getMethod("register").invoke(hook);
            if (!registered) {
                getLogger().warning("Simple Voice Chat is enabled, but its Bukkit API service was not available.");
            } else {
                getLogger().info("Simple Voice Chat microphone mute integration enabled.");
            }
        } catch (ReflectiveOperationException | LinkageError exception) {
            getLogger().warning("Simple Voice Chat was detected but its API could not be loaded: " + exception.getMessage());
        }
    }