anshu078_

MOB SMP CORE — COMPLETE MASTER DEVELOPMENT PROMPT

AV Studios | All-in-One SMP Management, Protection, Build Studio & Rank System

You are a senior Minecraft Paper/Purpur plugin developer, Java architect, anti-cheat engineer, database engineer and Minecraft server systems developer.

Your task is to design and develop a production-quality Minecraft plugin named MOB SMP Core, developed by AV Studios.

This is an all-in-one SMP management plugin. The server owner must be able to control the SMP lifecycle, world, players, protection, combat, anti-cheat, builds, items, dimensions, staff ranks and server administration through one plugin.

  1. PROJECT INFORMATION
  • Plugin: MOB SMP Core
  • Developer: AV Studios
  • Main Developer: ItsAnshuXD
  • Minecraft: Paper/Purpur 1.21.11
  • Java: 21
  • Language: Java
  • Build system: Gradle
  • Database: SQLite initially, MySQL-ready architecture
  • Integrations: LuckPerms, PlaceholderAPI, TAB

Requirements:

  • Modular architecture.
  • Secure UUID-based player identification.
  • Clean, maintainable Java code.
  • No unnecessary dependencies.
  • No memory leaks.
  • No unnecessary repeating tasks.
  • Async database operations where safe.
  • No unsafe asynchronous Bukkit world operations.
  • Restart-safe data and timers.
  • Configurable messages, sounds, permissions and settings.
  • Complete error handling and logging.
  • No fake features or incomplete implementations.
  1. DEVELOPMENT RULE

Before coding:

  1. Analyze the entire specification.
  2. Design the architecture.
  3. Create the module structure.
  4. Design database tables.
  5. Design command and permission systems.
  6. Identify possible exploits and conflicts.
  7. Explain technical limitations.
  8. Create a phased development roadmap.

Then implement and test the complete plugin.

Do not claim that a feature works unless it has actually been implemented and tested.

  1. CORE SMP MANAGEMENT

Commands:

/smp help /smp admin /smp status /smp setspawn /smp spawn /smp setworld /smp ready /smp start /smp stop /smp reload /smp maintenance

Features:

  • Custom main spawn.
  • Respawn at main spawn when no valid bed spawn exists.
  • Configurable SMP world.
  • Central admin GUI.
  • Persistent server state.
  • Maintenance mode.
  • Restart recovery.
  1. READY MODE

Command:

/smp ready

When executed:

  • Set temporary world border to 30×30.
  • Disable PvP.
  • Disable normal players' block breaking and placing.
  • Set normal players to Adventure mode.
  • Restrict unauthorized interactions.
  • Keep authorized admins able to build.
  • Activate READY status.

All restrictions must be enforced server-side.

  1. SMP START SYSTEM

Command:

/smp start

Expected behavior:

  • Display countdown from 10 to 1.
  • Show countdown to online players.
  • Broadcast: MOB SMP STARTED! GO GRIND!
  • Set normal players to Survival.
  • Expand border from 30×30 to 10,000×10,000.
  • Activate 30-minute PvP protection.
  • Show protection countdown through bossbar.
  • Send launch notifications.

Border expansion and PvP protection must use independent configurable timers.

Support restart-safe timers, duplicate-start prevention and safe handling of players joining during countdown.

  1. COMMUNITY BASE ZONE

Command:

/smp safe 200 circle

This creates a circular community building zone.

Exact behavior:

  • Center: command executor's current X/Z position.
  • Diameter: 200 blocks.
  • Bounding area: 200×200.
  • Radius: 100 blocks.
  • Save world UUID and coordinates.
  • Persistent after restarts.

Players inside can freely:

  • Break blocks.
  • Place blocks.
  • Build houses.
  • Create shops.
  • Build farms.
  • Decorate bases.
  • Modify their builds.

IMPORTANT:

This is NOT a protected region. It is a community building area.

Normal griefing rules still apply. Players must not destroy other players' builds without authorization.

Additional commands:

/smp safe info /smp safe remove /smp safe visualize

Community zone and guard regions must be independent.

  1. BEDROCK CIRCLE BOUNDARY

Command:

/smp fill circle 200 bedrock 100 1

Interpretation:

  • Current location X/Z = center.
  • Diameter = 200 blocks.
  • Bounding area = 200×200.
  • Material = Bedrock.
  • Y-level = 100.
  • Thickness = 1 block.
  • Circular outline, not a filled disk.

Synchronize the visible boundary with the configured safe-zone geometry when requested.

  1. WOODEN AXE SELECTION SYSTEM

Implement a WorldEdit-style selection wand.

Commands:

/smp wand /smp pos1 /smp pos2 /smp selection

  • Left-click = Position 1.
  • Right-click = Position 2.
  • Display coordinates.
  • Calculate dimensions and block count.
  • Show selection preview.
  • Per-player and per-world selection storage.
  • Configurable selection limits.
  1. GUARD REGION SYSTEM

Command:

/smp guard

Use the selected region to create a protected area.

Additional commands:

/smp guard remove /smp guard list /smp guard info

Features:

  • Normal players cannot break blocks.
  • Normal players cannot place blocks.
  • Configurable container protection.
  • Configurable interaction protection.
  • Explosion protection.
  • Admin/staff bypass permissions.
  • Multiple persistent regions.
  • Safe overlap handling.

Use this for server logos, decorations and special builds.

  1. ITEM LOCK SYSTEM

Commands:

/smp lock item /smp unlock item /smp lock netherite /smp unlock netherite

Default:

  • Netherite armor locked.
  • Netherite tools locked.
  • Netherite progression unavailable until unlocked.

Support configurable restrictions on:

  • Crafting.
  • Obtaining.
  • Equipping.
  • Using.
  • Transferring.

Check all relevant routes:

  • Crafting table.
  • 2×2 inventory crafting.
  • Crafter automation.
  • Shift-click crafting.
  • Smithing table.
  • Anvil transformations where relevant.
  • Villager trading.
  • Loot generation.
  • Plugin-generated items.
  • Other relevant vanilla and supported plugin acquisition routes.

Prevent duplication and bypass exploits.

Unlocking Netherite must restore the configured progression.

  1. DIMENSION LOCK SYSTEM

Default:

  • Nether locked.
  • End locked.

Commands:

/smp lock dimension /smp unlock dimension /smp lock dimension nether /smp unlock dimension nether /smp lock dimension end /smp unlock dimension end

Features:

  • Portal-entry restrictions.
  • Teleport-destination validation.
  • Nether portal checks.
  • End portal checks.
  • Plugin teleport checks.
  • Admin bypass.
  • Persistent dimension states.
  1. SCHEMATIC BUILD STUDIO

Upload directory:

plugins/MOBSMP/schematics/

Support:

  • Sponge .schem.
  • Compatible legacy .schematic files where supported.

Commands:

/smp schem list /smp schem info <name> /smp schem <name> <size> /smp schem rotate <degrees> /smp schem preview /smp schem paste /smp schem undo

Features:

  • Upload from hosting panel.
  • Paste at current location.
  • Resize and rotate.
  • Preview.
  • Block replacement options.
  • Configurable paste limits.
  • Undo/rollback.
  • Progress feedback.
  • Safe large-build processing.
  1. IMAGE TO MINECRAFT PIXEL ART

Upload PNG/JPG through hosting panel.

Directory:

plugins/MOBSMP/images/

Commands:

/smp image list /smp image info <name> /smp image preview <name> <width> <height> /smp image build <name> <width> <height> /smp image undo

Processing:

  1. Decode image.
  2. Validate file and dimensions.
  3. Resize to selected dimensions.
  4. Read pixel colors.
  5. Match colors to Minecraft blocks.
  6. Optionally apply dithering.
  7. Generate block-placement plan.
  8. Generate preview.
  9. Confirm build.
  10. Place blocks safely.

Features:

  • Wool, concrete and terracotta palettes.
  • Custom block palette.
  • Black-and-white mode.
  • Transparent pixels skipped.
  • Horizontal floor art.
  • Vertical wall art.
  • Rotation and direction.
  • Undo.
  • Image size limits.
  • Malicious image protection.
  1. ADVANCED FILL SYSTEM

Commands:

/smp fill circle <diameter> <material> <y> <thickness> /smp fill square <size> <material> <y> <thickness> /smp fill sphere <radius> <material> /smp fill cylinder <radius> <height> <material> /smp fill wall <size> <material> <height> /smp fill outline <shape> <size> <material> /smp fill undo

Features:

  • Material validation.
  • Admin-only access.
  • Preview and confirmation.
  • Maximum block-change limits.
  • Undo history.
  • Progress display.
  • World-height validation.
  • Safe chunk handling.
  • No server freezing.
  1. COMBAT SYSTEM

Features:

  • PvP combat tagging.
  • Configurable combat duration.
  • Bossbar timer.
  • Timer refresh on valid hits.
  • Block /smp spawn during combat.
  • Block /smp home during combat.
  • Block /smp tpa during combat.
  • Block unsafe teleportation.
  • Detect combat logout.
  • Configurable logout punishment.
  • Restore combat state after reconnect.
  • Custom death messages.
  • Kill streaks.
  • PvP statistics.

Default combat logout countdown: 10 seconds, configurable.

Do not punish legitimate disconnects caused by server crashes as intentional combat logging.

  1. ADVANCED ANTI-CHEAT

Detection modules:

  • Fly.
  • Speed.
  • KillAura.
  • Reach.
  • AutoClicker.
  • Scaffold.
  • NoFall.
  • Timer.
  • Velocity.
  • FastBreak.
  • Suspicious inventory behavior.
  • Xray-related suspicious behavior.

Features:

  • Server-side validation.
  • Violation tracking.
  • Configurable thresholds.
  • Staff alerts.
  • Evidence logs.
  • Latency awareness.
  • False-positive protection.
  • Configurable actions.
  • Per-check enable/disable.
  • Performance monitoring.

Never claim 100% detection accuracy.

Do not permanently ban players based on a single uncertain detection.

  1. ANTI-GRIEF AND BLOCK HISTORY

Track:

  • Block placement.
  • Block breaking.
  • Container access.
  • Important interactions.
  • Explosion-related destruction.
  • Region violations.

Commands:

/smp inspect /smp history /smp lookup <player> /smp rollback <player> /smp restore <player>

Save UUID, world, coordinates, previous/new block state, timestamps and event information.

Features:

  • Staff investigation.
  • Rollback.
  • Restore.
  • Retention limits.
  • Database storage.
  • Permission protection.
  1. HOMES SYSTEM

Player commands:

/smp sethome /smp home

Default:

  • One home per player.

Admin commands:

/smp homes <player> /smp sethomes <player> <amount> /smp removehome <player>

Features:

  • UUID-based storage.
  • Extra homes assigned individually.
  • Safe teleportation.
  • Combat restrictions.
  • Configurable delay.
  • Movement/damage cancellation.
  1. TPA SYSTEM

Only provide:

/smp tpa <player> /smp tpaccept

Do NOT add /tpahere or /tpdeny.

Features:

  • Request notification.
  • Request expiration.
  • Spam protection.
  • Teleport delay.
  • Movement/damage cancellation.
  • Combat restrictions.
  • Safe destination validation.
  1. MOB SMP RANK SYSTEM — IMPORTANT NEW MODULE

Develop a professional custom rank and prefix system integrated into MOB SMP Core.

There must be exactly these predefined ranks:

  1. OWNER
  2. CO-OWNER
  3. ADMIN
  4. MOD
  5. DEV
  6. MEDIA

Normal players have NO rank.

IMPORTANT DEFAULT PLAYER DISPLAY:

  • Do not display MEMBER.
  • Do not display DEFAULT.
  • Do not display any prefix.
  • Display only the player's normal Minecraft name.

Example:

Anshu123

Do not show:

[MEMBER] Anshu123 [DEFAULT] Anshu123

Rank Prefix Design

All assigned ranks must have:

  • Unique color.
  • Bold formatting.
  • Clean professional prefix.
  • Consistent spacing.
  • Correct display in chat and supported tab integrations.

Suggested design:

OWNER: Dark Red / Red, bold.

CO-OWNER: Gold, bold.

ADMIN: Bright Red, bold.

MOD: Blue, bold.

DEV: Aqua or Purple, bold.

MEDIA: Light Purple or Pink, bold.

Example displays:

[OWNER] Anshu123 [CO-OWNER] Player123 [ADMIN] Player123 [MOD] Player123 [DEV] Player123 [MEDIA] Player123

Use Minecraft Adventure components or a compatible formatting system.

Do not allow player-controlled formatting injection.

Prefix colors, text, bold setting and spacing must be configurable.

Rank Assignment Permissions

ONLY:

  • Server OPs.
  • Console.

may assign, remove or modify custom ranks.

Normal admins, moderators, developers and media players must NOT automatically have permission to assign ranks.

Commands:

/smp rank /smp rank list /smp rank info <rank> /smp rank set <player> <rank> /smp rank remove <player> /smp rank check <player>

Requirements:

  • OP-only rank assignment.
  • Console support.
  • Validate rank names.
  • Prevent unauthorized rank assignment.
  • Prevent rank escalation.
  • Log every assignment and removal.
  • Store rank against player UUID.
  • Persist rank after restart.
  • Notify player when rank changes.
  • Notify staff/admin as configured.
  • Prevent duplicate or conflicting assignments.

A player can have one primary custom rank at a time.

If no rank is assigned, show only their username.

Individual Rank Powers

Each staff rank must have individually configurable permissions.

Suggested initial permissions:

OWNER:

  • Full plugin administration.
  • Full SMP management.
  • All rank management.
  • Full guard and region management.
  • Full schematic and image building.
  • Full item/dimension lock management.
  • Full punishment control.
  • Full anti-cheat management.
  • Full rollback access.
  • Full admin GUI.
  • Full player management.

CO-OWNER:

  • Nearly all SMP management.
  • Player management.
  • Region management.
  • Punishment management.
  • Reports and history.
  • Schematic management.
  • Configurable restrictions on sensitive owner-only actions.

ADMIN:

  • Player management.
  • Kick, ban and warn.
  • Report investigation.
  • Block history.
  • Rollback if authorized.
  • SMP monitoring.
  • Configurable management permissions.

MOD:

  • Player moderation.
  • Reports.
  • Warnings and kicks.
  • Basic history inspection.
  • Staff alerts.
  • No unrestricted server configuration.

DEV:

  • Development and testing permissions.
  • Plugin diagnostic information.
  • Authorized test commands.
  • Configurable build/testing permissions.
  • No automatic access to punishment or rank management.

MEDIA:

  • Prefix and visual identity only.
  • No staff powers by default.
  • No admin permissions.
  • No moderation powers.
  • No rank management.
  • No automatic command bypass.

DEFAULT / UNRANKED:

  • No prefix.
  • Normal player permissions only.
  • No staff powers.

IMPORTANT:

  • Rank assignment and permissions must be separate systems.
  • Never grant OP automatically.
  • Never assume that a player with ADMIN rank should receive every powerful server permission.
  • All permissions must be configurable.
  • Only OP/console can assign custom ranks.
  • LuckPerms compatibility must be considered.
  • Do not overwrite unrelated LuckPerms permissions or groups.
  • The custom rank must not accidentally grant permission through prefix formatting alone.

Rank Priority

Suggested priority:

OWNER > CO-OWNER > ADMIN > MOD > DEV > MEDIA > UNRANKED.

The plugin must not allow a lower-ranked player to manage a higher-ranked player through any rank-management interface.

However, only OP/console can assign ranks regardless of this hierarchy.

Rank Display Integrations

Support:

  • Chat prefix.
  • TAB prefix.
  • Player list display.
  • Configurable prefix formatting.
  • PlaceholderAPI placeholders.

Suggested placeholders:

%mobsmp_rank% %mobsmp_prefix% %mobsmp_has_rank%

Unranked player behavior:

  • Rank placeholder should return an empty value.
  • Prefix placeholder should return an empty value.

Avoid duplicate prefixes when LuckPerms, TAB or another chat plugin already displays a prefix.

Provide configuration options to control which plugin is responsible for displaying prefixes.

  1. REPORTS AND PUNISHMENTS

Commands:

/smp report <player> <reason> /smp reports /smp reportview <id> /smp reportclose <id>

/smp warn <player> <reason> /smp kick <player> <reason> /smp ban <player> <reason> /smp tempban <player> <time> <reason> /smp unban <player> <reason>

Features:

  • Report status.
  • Evidence references.
  • Staff investigation.
  • Warning history.
  • Ban history.
  • Punishment reasons.
  • Staff identity.
  • Timestamps.
  • Configurable policies.
  1. PLAYER AND SERVER FEATURES

Include:

  • Player statistics.
  • Kills and deaths.
  • Playtime.
  • Kill streaks.
  • Join/quit messages.
  • First-join welcome.
  • AFK detection.
  • Anti-spawn-trap options.
  • Staff alerts.
  • Scheduled announcements.
  • Maintenance mode.
  • Custom MOTD.
  • Rules GUI.
  • PlaceholderAPI support.
  • TAB integration.
  • LuckPerms integration.
  1. CENTRAL ADMIN GUI

Command:

/smp admin

Create a professional inventory-based GUI with:

  • SMP Management.
  • Spawn Management.
  • Community Safe Zone.
  • Guard Regions.
  • World Border.
  • PvP Controls.
  • Item Locks.
  • Dimension Locks.
  • Schematic Manager.
  • Image Builder.
  • Fill Tools.
  • Combat Settings.
  • Anti-Cheat.
  • Block History.
  • Player Reports.
  • Punishments.
  • Player Statistics.
  • Rank Management.
  • Announcements.
  • Configuration.

GUI requirements:

  • Clear item names and descriptions.
  • Permission checks.
  • Confirmation menus.
  • No fake buttons.
  • All actions must execute real plugin functions.

Rank management GUI must be OP/console-authorized only.

  1. PERMISSIONS

Create granular permissions.

Suggested nodes:

mobsmp.admin mobsmp.staff mobsmp.spawn mobsmp.home mobsmp.home.extra mobsmp.tpa mobsmp.report mobsmp.guard mobsmp.guard.bypass mobsmp.fill mobsmp.schematic mobsmp.image mobsmp.lock mobsmp.dimension mobsmp.combat.bypass mobsmp.anticheat.bypass mobsmp.history mobsmp.rollback mobsmp.punishment mobsmp.safezone.admin

Rank-specific permission nodes:

mobsmp.rank.owner mobsmp.rank.coowner mobsmp.rank.admin mobsmp.rank.mod mobsmp.rank.dev mobsmp.rank.media

mobsmp.rank.assign mobsmp.rank.remove mobsmp.rank.manage

IMPORTANT:

  • Rank assignment must have a hard OP/console authorization check.
  • Do not trust LuckPerms rank nodes alone for rank assignment.
  • Custom rank labels must never automatically grant OP.
  • Media and unranked players receive no staff permissions.
  1. DATABASE AND CONFIGURATION

Use SQLite by default and design MySQL-ready abstraction.

Persist:

  • Player UUIDs.
  • Custom ranks.
  • Rank assignment history.
  • Homes.
  • Safe-zone configuration.
  • Guard regions.
  • Block history.
  • Item locks.
  • Dimension locks.
  • Combat state.
  • Reports.
  • Punishments.
  • Player statistics.
  • Build history.
  • Admin settings.

Configuration files:

config.yml messages.yml permissions.yml ranks.yml worlds.yml safezones.yml guards.yml locks.yml combat.yml anticheat.yml schematics.yml images.yml database.yml

The ranks.yml file must define:

  • Rank names.
  • Prefix text.
  • Prefix colors.
  • Bold formatting.
  • Display priority.
  • Permission mappings.
  • Default rank powers.
  • Rank-specific configurable abilities.
  1. SECURITY AND PERFORMANCE

Protect against:

  • Item duplication.
  • Crafter-based lock bypass.
  • Portal and teleport bypass.
  • Unauthorized region modification.
  • Unauthorized schematic access.
  • Malicious image uploads.
  • Oversized fill operations.
  • Rollback abuse.
  • Rank assignment abuse.
  • Rank escalation.
  • Permission bypass.
  • Database corruption.
  • Restart-related data loss.
  • Excessive event processing.
  • Main-thread blocking.

Use safe operation queues and bounded processing.

Validate all player input and admin command arguments.

  1. TESTING

Test on Paper and Purpur 1.21.11 with Java 21.

Test:

  • Fresh installation.
  • Database creation.
  • Restart recovery.
  • SMP ready/start lifecycle.
  • Border expansion.
  • Community zone building.
  • Guard protection.
  • Item locking through manual and automated crafting.
  • Nether/End restrictions.
  • Schematic paste and undo.
  • Image conversion.
  • Fill geometry.
  • Combat logout.
  • Home and TPA.
  • Anti-cheat false positives.
  • Report and punishment workflows.
  • Rank assignment authorization.
  • Rank persistence.
  • Rank prefix formatting.
  • Unranked players displaying no prefix.
  • Rank-specific permissions.
  • Media receiving no staff powers.
  • LuckPerms/TAB integration.
  • Multiple simultaneous players.

Do not report a test as passed unless it has actually passed.

  1. FINAL DELIVERABLES

Provide:

  1. Complete Java source code.
  2. Gradle build files.
  3. Plugin metadata.
  4. All modules and resource files.
  5. Database implementation.
  6. Configuration examples.
  7. Permissions documentation.
  8. Rank documentation.
  9. Command documentation.
  10. Installation instructions.
  11. Testing report.
  12. Compiled MOB-SMP-Core.jar.

The final JAR must install on Paper/Purpur 1.21.11.

No fake implementations, empty methods, unfinished TODOs or nonfunctional advertised features.

If the project cannot be completed in one generation, develop it in phases with clear interfaces and compatibility.

FINAL OBJECTIVE

Build MOB SMP Core into a powerful, stable, secure, production-quality all-in-one Minecraft SMP management plugin for AV Studios.

The plugin must control:

  • SMP lifecycle.
  • Spawn and community bases.
  • Safe zones and guard regions.
  • World borders.
  • Item and dimension progression.
  • Combat and logout detection.
  • Anti-cheat and anti-grief.
  • Player reports and punishments.
  • Homes and TPA.
  • Schematic building.
  • Image-to-pixel-art building.
  • WorldEdit-style fill operations.
  • Staff ranks and permissions.
  • Central administration.

Prioritize actual functionality, security, performance and maintainability over feature count.

The finished product should be reliable enough for a public multiplayer SMP server.

Kodari AI
KodariNov 1 at 10:40 am 2
MobSmpCore
An all-in-one SMP management plugin for Paper/Purpur 1.21.11 with Java 21. It manages the SMP lifecycle with ready/start modes, world borders, and PvP protection. Features include a community safe zone, guard regions with a wooden axe selection system, item and dimension locks, schematic and image building, advanced fill tools, combat tagging, an anti-cheat, block history, homes, TPA, reports, punishments, and a custom rank system with OP-only assignment. It uses SQLite with MySQL-ready architecture and integrates with LuckPerms, PlaceholderAPI, and TAB.
  1. Architecture: Paper plugin with lifecycle/protection event handling, a dedicated rank service, and a SQLite-backed rank store; persisted SMP settings remain in YAML.

  2. Database: UUID-keyed ranks plus an assignment/removal audit table; SQLite is the initial backend, with the store interface isolating it for a future MySQL adapter.

  3. Scope and safety: this first phase implements SMP ready/start/stop, spawn/world, maintenance, community-zone metadata, and ranks. It does not advertise unimplemented systems such as schematic/image building, rollback, punishments, TPA, or anti-cheat.

  4. Limitations and roadmap: rank changes initially target online players; the community zone records build-area geometry but does not claim to prevent griefing. Next phases can add guard regions/history, homes/TPA and moderation, then build tools and integrations. Restart handling restores lifecycle and protection timers; detection systems require separate validation before being called anti-cheat.

Created the initial MOB SMP Core foundation: Gradle setup, plugin metadata, configurable messages and rank prefixes, SMP lifecycle commands, and an asynchronous SQLite-backed rank store with assignment history.

Implemented in this phase:

  • /smp status, setworld, setspawn, spawn, ready, start, stop, and maintenance.

  • Ready-mode build and interaction restrictions, plus countdown, world-border expansion, and restart-aware PvP protection.

  • Persistent spawn and community-zone geometry. The zone is metadata only; it does not protect builds from griefing.

  • Six configurable cosmetic ranks, UUID persistence, chat/tab display, and rank assignment restricted directly to OPs or console.

Still out of scope for this phase: combat tagging and spawn restrictions, guard regions, homes/TPA, anti-cheat, history/rollback, punishments, GUI, build tools, and LuckPerms/TAB/PlaceholderAPI integrations. Rank changes currently require the target to be online; rank labels do not grant permissions. I have not tested this against a Paper/Purpur server, so no test pass is claimed.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
manifest.kod
settings.gradle
Code
13 1,263
src/main/java/com/avstudios/mobsmp/MobSmpPlugin.java
package com.avstudios.mobsmp;

import com.avstudios.mobsmp.command.SmpCommand;
import com.avstudios.mobsmp.data.RankStore;
import com.avstudios.mobsmp.data.SqliteRankStore;
import com.avstudios.mobsmp.rank.RankService;
import com.avstudios.mobsmp.listener.SmpListener;
import java.io.File;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.plugin.java.JavaPlugin;

public final class MobSmpPlugin extends JavaPlugin {
    private RankStore rankStore;
    private RankService rankService;
    private org.bukkit.boss.BossBar protectionBar;
    private BukkitTask countdownTask;
    private BukkitTask protectionTask;
    private int lastCountdownAnnouncement = Integer.MAX_VALUE;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        saveIfMissing("ranks.yml");
        saveIfMissing("messages.yml");
        rankStore = new SqliteRankStore(new File(getDataFolder(), "mobsmp.db"), getLogger());
        rankService = new RankService(this, rankStore);
        Bukkit.getPluginManager().registerEvents(new SmpListener(this), this);
        getCommand("smp").setExecutor(new SmpCommand(this));
        getCommand("smp").setTabCompleter(new SmpCommand(this));
        recoverLifecycle();
    }

    private void saveIfMissing(String name) {
        if (!new File(getDataFolder(), name).exists()) {
            saveResource(name, false);
        }
    }

    @Override
    public void onDisable() {
        cancelTask(countdownTask);
        cancelTask(protectionTask);
        if (protectionBar != null) {
            protectionBar.removeAll();
        }
        if (rankStore != null) {
            rankStore.close();
        }
        HandlerList.unregisterAll(this);
    }

    private void cancelTask(BukkitTask task) {
        if (task != null) {
            task.cancel();
        }
    }

    public RankService getRankService() {
        return rankService;
    }

    public String getState() {
        return getConfig().getString("lifecycle.state", "STOPPED").toUpperCase(Locale.ROOT);
    }

    public boolean isReady() {
        return getState().equals("READY");
    }

    public boolean isCountdown() {
        return getState().equals("COUNTDOWN");
    }

    public boolean isRunning() {
        return getState().equals("RUNNING");
    }

    public boolean isMaintenance() {
        return getConfig().getBoolean("maintenance.enabled", false);
    }

    public World getSmpWorld() {
        return Bukkit.getWorld(getConfig().getString("world", "world"));
    }

    public void setSmpWorld(World world) {
        getConfig().set("world", world.getName());
        saveConfig();
    }

    public void setMaintenance(boolean enabled) {
        getConfig().set("maintenance.enabled", enabled);
        saveConfig();
    }

    public String message(String key, String... replacements) {
        File file = new File(getDataFolder(), "messages.yml");
        org.bukkit.configuration.file.YamlConfiguration messages =
                org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(file);
        String text = messages.getString(key, "&cMissing message: " + key);
        for (int i = 0; i + 1 < replacements.length; i += 2) {
            text = text.replace(replacements[i], replacements[i + 1]);
        }
        return ChatColor.translateAlternateColorCodes('&',
                ChatColor.translateAlternateColorCodes('&', messages.getString("prefix", "")) + text);
    }

    public Location getConfiguredSpawn() {
        String worldId = getConfig().getString("spawn.world-uuid", "");
        if (worldId.isBlank()) {
            return null;
        }
        World world;
        try {
            UUID uuid = UUID.fromString(worldId);
            world = Bukkit.getWorld(uuid);
        } catch (IllegalArgumentException ignored) {
            getLogger().warning("Invalid spawn world UUID in config.yml.");
            return null;
        }
        if (world == null) {
            world = getSmpWorld();
        }
        if (world == null) {
            return null;
        }
        return new Location(world,
                getConfig().getDouble("spawn.x", 0.5),
                getConfig().getDouble("spawn.y", 80.0),
                getConfig().getDouble("spawn.z", 0.5),
                (float) getConfig().getDouble("spawn.yaw", 0.0),
                (float) getConfig().getDouble("spawn.pitch", 0.0));
    }

    public void setSpawn(Location location) {
        getConfig().set("spawn.world-uuid", location.getWorld().getUID().toString());
        getConfig().set("spawn.x", location.getX());
        getConfig().set("spawn.y", location.getY());
        getConfig().set("spawn.z", location.getZ());
        getConfig().set("spawn.yaw", location.getYaw());
        getConfig().set("spawn.pitch", location.getPitch());
        saveConfig();
    }

    public void enterReadyMode() {
        cancelTask(countdownTask);
        cancelTask(protectionTask);
        countdownTask = null;
        protectionTask = null;
        if (protectionBar != null) {
            protectionBar.removeAll();
            protectionBar.setVisible(false);
            protectionBar = null;
        }
        getConfig().set("lifecycle.state", "READY");
        getConfig().set("lifecycle.countdown-ends-at", 0L);
        getConfig().set("lifecycle.protection-ends-at", 0L);
        getConfig().set("lifecycle.border-ends-at", 0L);
        saveConfig();
        applyReadyWorldSettings();
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (!player.hasPermission("mobsmp.ready.bypass")) {
                player.setGameMode(org.bukkit.GameMode.ADVENTURE);
            }
        }
    }

    private void applyReadyWorldSettings() {
        World world = getSmpWorld();
        if (world != null) {
            world.setPVP(false);
            world.getWorldBorder().setSize(getConfig().getDouble("border.ready-size", 30.0));
        }
    }

    public boolean beginStartCountdown() {
        if (isCountdown()) {
            return false;
        }
        if (!isReady()) {
            return false;
        }
        int seconds = Math.max(1, getConfig().getInt("timers.start-countdown-seconds", 10));
        long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds);
        getConfig().set("lifecycle.state", "COUNTDOWN");
        getConfig().set("lifecycle.countdown-ends-at", end);
        saveConfig();
        lastCountdownAnnouncement = seconds;
        countdownTask = Bukkit.getScheduler().runTaskTimer(this, this::tickCountdown, 0L, 20L);