Newer
Older
TreasureChest / src / main / java / de / iani / treasurechest / TreasureChest.java
@Brokkonaut Brokkonaut on 4 Jul 2017 8 KB Transfer to git
package de.iani.treasurechest;

import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Level;

import net.milkbowl.vault.economy.Economy;

import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

import de.iani.playerUUIDCache.CachedPlayer;
import de.iani.playerUUIDCache.PlayerUUIDCache;

public class TreasureChest extends JavaPlugin implements TreasureChestAPI {
    private PriceChestData data;

    private Location chestLocation;

    private Random random;

    // private PlayerUUIDTools uuidTools;

    private boolean hasEconomy;

    private Economy economy;

    private PlayerUUIDCache playerUUIDCache;

    @Override
    public void onEnable() {
        random = new Random();
        setupEconomy();
        // uuidTools = new PlayerUUIDTools(this);
        playerUUIDCache = (PlayerUUIDCache) getServer().getPluginManager().getPlugin("PlayerUUIDCache");
        readConfig();
        // chestLocation = new Location(getServer().getWorlds().get(0), 308, 127, -879);
        data = new PriceChestData(this);
        getCommand("pricechest").setExecutor(new PriceChestCommandExecutor(this));

        getServer().getPluginManager().registerEvents(new ChestInventoryListener(this), this);
        getServer().getPluginManager().registerEvents(new PlayerEventListener(this), this);
        getServer().getScheduler().runTaskTimer(this, new Runnable() {
            @Override
            public void run() {
                createParticles();
            }
        }, 1, 1);

        getServer().getScheduler().runTaskTimer(this, new Runnable() {
            @Override
            public void run() {
                doGC();
            }
        }, 8456, 140000);
    }

    public PlayerUUIDCache getPlayerUUIDCache() {
        return playerUUIDCache;
    }

    @Override
    public boolean addItem(String player, ItemStack displayItem, ItemStack[] items, int money) {
        if (!getServer().isPrimaryThread()) {
            return false;
        }
        CachedPlayer id = playerUUIDCache.getPlayerFromNameOrUUID(player, true);
        if (id == null) {
            return false;
        }
        return addItem(id.getUUID(), displayItem, items, money);
    }

    @Override
    public boolean addItem(OfflinePlayer player, ItemStack displayItem, ItemStack[] items, int money) {
        if (!getServer().isPrimaryThread()) {
            return false;
        }
        return addItem(player.getUniqueId(), displayItem, items, money);
    }

    private boolean addItem(UUID player, ItemStack displayItem, ItemStack[] items, int money) {
        if (displayItem == null || displayItem.getAmount() == 0 || displayItem.getType() == Material.AIR) {
            return false;
        }
        ArrayList<ItemStack> copied = new ArrayList<>();
        for (ItemStack is : items) {
            if (is != null && is.getAmount() > 0 && is.getType() != Material.AIR) {
                copied.add(is);
            }
        }
        items = copied.toArray(new ItemStack[copied.size()]);

        PlayerTreasureChestContent content = getData().getChestContent(player);
        content.addItem(new TreasureChestItem(displayItem, items, money));
        return true;
    }

    protected void doGC() {
        data.doGC();
    }

    private void readConfig() {
        // saveDefaultConfig();
        FileConfiguration config = getConfig();
        ConfigurationSection section = config.getConfigurationSection("chestLocation");
        if (section != null) {
            String worldName = section.getString("world");
            int x = section.getInt("x");
            int y = section.getInt("y");
            int z = section.getInt("z");
            if (worldName != null) {
                World world = getServer().getWorld(worldName);
                if (world != null) {
                    chestLocation = new Location(world, x, y, z);
                }
            }
        }
    }

    public void saveConfig() {
        FileConfiguration config = getConfig();
        if (chestLocation == null || chestLocation.getWorld() == null) {
            config.set("chestLocation", null);
        } else {
            ConfigurationSection section = config.getConfigurationSection("chestLocation");
            if (section == null) {
                section = config.createSection("chestLocation");
            }
            section.set("world", chestLocation.getWorld().getName());
            section.set("x", chestLocation.getBlockX());
            section.set("y", chestLocation.getBlockY());
            section.set("z", chestLocation.getBlockZ());
        }
        super.saveConfig();
    }

    // public PlayerUUIDTools getUUIDTools()
    // {
    // return uuidTools;
    // }

    public PriceChestData getData() {
        return data;
    }

    public Location getChestLocation() {
        return chestLocation;
    }

    protected void createParticles() {
        if (random.nextInt(10) == 0 && chestLocation != null) {
            Location playerLocation = new Location(null, 0, 0, 0);
            for (Player player : getServer().getOnlinePlayers()) {
                player.getLocation(playerLocation);
                if (playerLocation.getWorld() == chestLocation.getWorld()) {
                    double dx = playerLocation.getX() - chestLocation.getX();
                    double dy = playerLocation.getY() - chestLocation.getY();
                    double dz = playerLocation.getZ() - chestLocation.getZ();
                    double dsquared = dx * dx + dy * dy + dz * dz;
                    if (dsquared < 16 * 16) {
                        if (!data.getChestContent(player.getUniqueId()).isEmpty()) {
                            player.playEffect(chestLocation, Effect.MOBSPAWNER_FLAMES, null);
                        }
                    }
                }
            }
        }
    }

    public void sendMessage(CommandSender p, String text) {
        sendMessage(p, text, false);
    }

    public void sendMessage(CommandSender p, String text, boolean error) {
        p.sendMessage(ChatColor.BLUE + "[TC] " + (error ? ChatColor.DARK_RED : ChatColor.YELLOW) + text);
    }

    public void setChestLocation(Location location) {
        chestLocation = location;
        saveConfig();
    }

    private void setupEconomy() {
        try {
            RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
            if (economyProvider != null) {
                economy = economyProvider.getProvider();
                hasEconomy = true;
            } else {
                getLogger().severe("Kein Economy-Plugin! Es können keine Preisgelder ausgezahlt werden!");
            }
        } catch (Throwable e) {
            getLogger().severe("Vault nicht gefunden! Es können keine Preisgelder ausgezahlt werden!");
        }
    }

    public boolean hasEconomy() {
        return hasEconomy;
    }

    public void giveMoney(Player player, int amount) {
        if (hasEconomy) {
            try {
                economy.depositPlayer(player, amount);
            } catch (Throwable e) {
                getLogger().log(Level.SEVERE, "Error paying money", e);
            }
        }
    }

    public String formatMoney(int amount) {
        if (hasEconomy) {
            try {
                return economy.format(amount);
            } catch (Throwable e) {
                getLogger().log(Level.SEVERE, "Error formating money", e);
            }
        }
        return Integer.toString(amount);
    }

    public static String capitalize(String s, boolean replaceUnderscores) {
        char[] cap = s.toCharArray();
        boolean lastSpace = true;
        for (int i = 0; i < cap.length; i++) {
            if (cap[i] == '_') {
                if (replaceUnderscores) {
                    cap[i] = ' ';
                }
                lastSpace = true;
            } else if (cap[i] >= '0' && cap[i] <= '9') {
                lastSpace = true;
            } else {
                if (lastSpace) {
                    cap[i] = Character.toUpperCase(cap[i]);
                } else {
                    cap[i] = Character.toLowerCase(cap[i]);
                }
                lastSpace = false;
            }
        }
        return new String(cap);
    }

}