Newer
Older
ChallengeSystem / src / main / java / de / fanta / challenges / Challenges.java
@fanta fanta on 6 Jun 2022 17 KB zeug halt mal wieder
package de.fanta.challenges;

import de.cubeside.nmsutils.NMSUtils;
import de.fanta.challenges.challenges.AllItemsChallenge;
import de.fanta.challenges.challenges.MLGChallenge;
import de.fanta.challenges.challenges.RandomDropsChallenge;
import de.fanta.challenges.commands.CommandRegistration;
import de.fanta.challenges.events.EventStatusChangedEvent;
import de.fanta.challenges.events.PlayerCountChangedEvent;
import de.fanta.challenges.events.ServerStatusChangedEvent;
import de.fanta.challenges.events.TimerChangedEvent;
import de.fanta.challenges.guis.BackpackGui;
import de.fanta.challenges.listeners.EventRegistration;
import de.fanta.challenges.scoreboard.ScoreBoardManager;
import de.fanta.challenges.scoreboard.ScoreManager;
import de.fanta.challenges.utils.ChatUtil;
import de.fanta.challenges.utils.VanishUtils;
import de.fanta.challenges.utils.guiutils.GUIUtils;
import org.apache.commons.io.FileUtils;
import org.bukkit.BanList;
import org.bukkit.Bukkit;
import org.bukkit.Difficulty;
import org.bukkit.GameRule;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class Challenges extends JavaPlugin {

    public static Logger LOGGER;
    private static Challenges plugin;
    public File RndDropsConfigFile;
    public FileConfiguration RndDropsConfig;
    public FileConfiguration AllItemsConfig;
    public FileConfiguration ServerConfig;
    public RandomDropsChallenge rndDrops;
    public NMSUtils nmsUtils;
    public String texturepacklink = null;
    public int resetTaskId = -1;
    private String PREFIX;
    private String GUIPREFIX;
    private File backpackConfigFile;
    private FileConfiguration BackpackConfig;
    private File AllItemsConfigFile;
    private File ServerConfigFile;
    private Timer timer;
    private VanishUtils vanish;
    private BackpackGui backpack;
    private ScoreBoardManager sbManager;
    private ScoreManager scoreManager;
    private UUID texturepackid = null;
    private Player currentEditor;

    private OfflinePlayer firstEditor;

    private boolean waitingForShutdown;

    private ServerType serverType;

    private int protocolVersion;

    public FileConfiguration ItemConfig;
    public File ItemConfigFile;

    private static ArrayList<Material> not_available_materials = new ArrayList<>();
    private static ArrayList<Material> materials = new ArrayList<>();

    public static Challenges getPlugin() {
        return plugin;
    }

    @Override
    public void onEnable() {
        LOGGER = getLogger();
        plugin = this;
        nmsUtils = getServer().getServicesManager().load(NMSUtils.class);

        protocolVersion = Bukkit.getUnsafe().getProtocolVersion();

        this.timer = new Timer(this);
        this.rndDrops = new RandomDropsChallenge();

        this.scoreManager = new ScoreManager(this);
        this.vanish = new VanishUtils(this);

        saveDefaultConfig();
        reloadConfig();
        createServerConfig();
        createItemConfig();

        serverType = ServerType.valueOf(getServerConfig().getString("servertype"));

        String prefix = serverType.getPrefix();
        PREFIX = ChatUtil.BLUE + "[" + ChatUtil.GREEN + prefix + ChatUtil.BLUE + "]";
        GUIPREFIX = ChatUtil.GREEN + prefix;

        createRndDropsConfig();
        createAllItemsConfig();
        createBackpackConfig();

        this.backpack = new BackpackGui(getConfig().getInt("backpack_size") * 9);

        new CommandRegistration(this).registerCommands();
        new EventRegistration(this).registerEvents();

        this.backpack.loadInventoryFromConfig();
        this.sbManager = new ScoreBoardManager(this);

        Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
            World world = Bukkit.getWorld("world");
            if (plugin.getServerType() != ServerType.ADVENTURE) {
                world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false);
            }
            MLGChallenge.checkMLGWorld();
            setPvP(getConfig().getBoolean("pvp"));
            if (plugin.getServerType() != ServerType.ADVENTURE) {
                plugin.getSBManager().initScoreboard();
            }
        }, 1L);

        if (getConfig().getBoolean("World_Reset")) {
            if (!getConfig().getBoolean("firsttimerstart")) {
                timer.setTime(0);
            }
            File config = new File(plugin.getDataFolder(), "config.yml");
            config.delete();
            reloadConfig();
            saveConfig();
            this.backpack.clearConfig();
            AllItemsChallenge.clearConfig();
            this.rndDrops.shuffleItems();
            this.rndDrops.saveItems();
            this.rndDrops.loadItems();
        } else {
            this.getBackpack().resize(getConfig().getInt("backpack_size") * 9);
            this.rndDrops.loadItems();
            this.backpack.loadInventoryFromConfig();
            timer.setTime(getConfig().getInt("timertime"));
            AllItemsChallenge.loadItems();
        }


        if (plugin.getServerType() == ServerType.ADVENTURE) {
            startResetTask();

            File texturepack = new File("world/resources.zip");
            if (texturepack.exists()) {
                texturepackid = UUID.randomUUID();
                File texturepackdownload = new File("/home/web/fanta/AdventureMap-TexturePacks/" + texturepackid + "/");
                File temp = new File(texturepackid.toString());
                try {
                    FileUtils.forceMkdir(temp);
                    FileUtils.copyFileToDirectory(texturepack, temp, false);
                    File renameTP = new File(texturepackid.toString() + "/" + "resources.zip");
                    File renamedTP = new File(texturepackid.toString() + "/" + texturepackid + ".zip");
                    renameTP.renameTo(renamedTP);
                    if (temp.isDirectory()) {
                        FileUtils.moveDirectory(temp, texturepackdownload);
                    } else {
                        Bukkit.getLogger().info("Ordner nicht da!");
                    }

                    texturepacklink = "https://fantacs.de/AdventureMap-TexturePacks/" + texturepackid + "/" + texturepackid + ".zip";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            getConfig().set("showtimer", false);

        } else {
            getConfig().set("showtimer", true);
        }

        if (getConfig().getBoolean("allitems")) {
            AllItemsChallenge.start();
        }
        for (String string : getItemConfig().getStringList("items")) {
            Material material = Material.valueOf(string);
            not_available_materials.add(material);
        }

        for (Material material : Material.values()) {
            if (material.isItem() && !material.isAir()) {
                materials.add(material);
            }
        }

        Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
            EventRegistration.pM.callEvent(new ServerStatusChangedEvent(true));
            EventRegistration.pM.callEvent(new TimerChangedEvent(timer.isRunning()));
            EventRegistration.pM.callEvent(new PlayerCountChangedEvent(Bukkit.getOnlinePlayers().size() - plugin.getVanish().countVanishPlayers()));
        }, 200L);
        getLogger().info("Plugin loaded!");
    }

    @Override
    public void onDisable() {
        Bukkit.getBanList(BanList.Type.NAME).getBanEntries().forEach(b -> Bukkit.getBanList(BanList.Type.NAME).pardon(b.getTarget()));
        if (!getConfig().getBoolean("World_Reset")) {
            this.backpack.saveInventoryToConfig();
            getConfig().set("backpack_size", backpack.getSize() / 9);
        } else {
            this.backpack.clearConfig();
            AllItemsChallenge.clearConfig();
        }
        try {
            this.RndDropsConfig.save(this.RndDropsConfigFile);
            this.AllItemsConfig.save(this.getAllItemsConfigFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        getConfig().set("timertime", timer.getTime());
        if (getConfig().getBoolean("event.enabled")) {
            GUIUtils.setConfig("event.enabled", false);
            Bukkit.getPluginManager().callEvent(new EventStatusChangedEvent(false));
            getScoreManager().saveScores(null);
        }
        if (texturepackid != null) {
            File temp = new File(texturepackid.toString());
            if (temp.isDirectory()) {
                temp.delete();
            }
        }

        saveConfig();
        getLogger().info("Plugin unloaded");
    }

    public RandomDropsChallenge getRandomDropsManager() {
        return this.rndDrops;
    }

    public FileConfiguration getBackpackConfig() {
        return this.BackpackConfig;
    }

    private void createBackpackConfig() {
        this.backpackConfigFile = new File(getDataFolder(), "backpack.yml");
        if (!this.backpackConfigFile.exists()) {
            this.backpackConfigFile.getParentFile().mkdirs();
            saveResource("backpack.yml", false);
        }
        this.BackpackConfig = new YamlConfiguration();
        try {
            this.BackpackConfig.load(this.backpackConfigFile);
        } catch (InvalidConfigurationException | IOException e) {
            e.printStackTrace();
        }
    }

    public FileConfiguration getRndDropsConfig() {
        return this.RndDropsConfig;
    }

    private void createRndDropsConfig() {
        this.RndDropsConfigFile = new File(getDataFolder(), "rnddrops.yml");
        if (!this.RndDropsConfigFile.exists()) {
            this.RndDropsConfigFile.getParentFile().mkdirs();
            saveResource("rnddrops.yml", false);
        }
        this.RndDropsConfig = new YamlConfiguration();
        try {
            this.RndDropsConfig.load(this.RndDropsConfigFile);
        } catch (IOException | org.bukkit.configuration.InvalidConfigurationException e) {
            e.printStackTrace();
        }
    }

    public FileConfiguration getAllItemsConfig() {
        return this.AllItemsConfig;
    }

    private void createAllItemsConfig() {
        this.AllItemsConfigFile = new File(getDataFolder(), "allitems.yml");
        if (!this.getAllItemsConfigFile().exists()) {
            this.getAllItemsConfigFile().getParentFile().mkdirs();
            saveResource("allitems.yml", false);
        }
        this.AllItemsConfig = new YamlConfiguration();
        try {
            this.AllItemsConfig.load(this.getAllItemsConfigFile());
        } catch (IOException | org.bukkit.configuration.InvalidConfigurationException e) {
            e.printStackTrace();
        }
    }

    public FileConfiguration getServerConfig() {
        return ServerConfig;
    }

    private void createServerConfig() {
        ServerConfigFile = new File(getDataFolder(), "serverconfig.yml");
        if (!ServerConfigFile.exists()) {
            ServerConfigFile.getParentFile().mkdirs();
            saveResource("serverconfig.yml", false);
        }
        this.ServerConfig = new YamlConfiguration();
        try {
            ServerConfig.load(ServerConfigFile);
        } catch (IOException | org.bukkit.configuration.InvalidConfigurationException e) {
            e.printStackTrace();
        }
    }

    public FileConfiguration getItemConfig() {
        return ItemConfig;
    }
    private void createItemConfig() {
        ItemConfigFile = new File(getDataFolder(), "items.yml");
            ItemConfigFile.getParentFile().mkdirs();
            saveResource("items.yml", true);
        this.ItemConfig = new YamlConfiguration();
        try {
            ItemConfig.load(ItemConfigFile);
        } catch (IOException | org.bukkit.configuration.InvalidConfigurationException e) {
            e.printStackTrace();
        }
    }

    public ScoreBoardManager getSBManager() {
        return this.sbManager;
    }

    public Player getCurrentEditor() {
        return currentEditor;
    }

    public void setCurrentEditor(Player currentEditor) {
        this.currentEditor = currentEditor;
        plugin.setFirstEditor(currentEditor);
        if (currentEditor != null) {
            ChatUtil.sendNormalMessage(currentEditor, "Du bist nun der Editor dieser Lobby!");
            ChatUtil.sendNormalMessage(currentEditor, "Alle Befehle und Funktionen vom Challenge Plugin findest du in unserem Wiki.");
            ChatUtil.sendNormalMessage(currentEditor, "Hier Klicken --> https://wiki.cubeside.de/Challenge");
            ChatUtil.sendBrodcastMessage(ChatUtil.BLUE + currentEditor.getName() + ChatUtil.GREEN + " ist nun der Editor dieser Lobby!");
        }
    }

    public OfflinePlayer getFirstEditor() {
        return firstEditor;
    }

    public void setFirstEditor(Player firstEditor) {
        if (this.firstEditor == null) {
            this.firstEditor = firstEditor;
        }
    }

    public void updateEditor() {
        Random random = new Random();
        Player randomPlayer = null;
        Player oldEditor = plugin.getCurrentEditor();

        List<Player> onlinePlayersWithPermission = Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("Challenges.editor")).distinct().collect(Collectors.toList());
        onlinePlayersWithPermission.remove(oldEditor);
        if (onlinePlayersWithPermission.size() > 0) {
            int rnd = random.nextInt(onlinePlayersWithPermission.size());
            randomPlayer = onlinePlayersWithPermission.get(rnd);
        } else {
            ArrayList<String> onlinePlayers = Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toCollection(ArrayList::new));
            List<String> vanishPlayers = plugin.getVanish().getVanishPlayerList();
            onlinePlayers.removeAll(vanishPlayers);
            onlinePlayers.remove(oldEditor.getName());

            if (onlinePlayers.size() > 0) {
                int rnd = random.nextInt(onlinePlayers.size());
                randomPlayer = Bukkit.getPlayer(onlinePlayers.get(rnd));
            }
        }
        plugin.setCurrentEditor(randomPlayer);
    }

    public boolean hasEditor() {
        return currentEditor != null;
    }

    public boolean isEditor(Player player) {
        return hasEditor() && currentEditor.getUniqueId().equals(player.getUniqueId());
    }

    public void startResetTask() {
        resetTaskId = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "reset confirm"), 3 * 60 * 20);
    }

    public void stopResetTask() {
        Bukkit.getScheduler().cancelTask(resetTaskId);
        resetTaskId = -1;
    }

    public void delteTexturePack() {
        File texturepackdownload = new File("/home/web/fanta/AdventureMap-TexturePacks/" + texturepackid + "/");
        if (texturepackdownload.isDirectory()) {
            texturepackdownload.delete();
        }
    }

    public void setPvP(Boolean value) {
        for (World w : plugin.getServer().getWorlds()) {
            if (w != null) {
                w.setPVP(value);
            }

        }
    }

    public boolean getPvP() {
        return Bukkit.getWorld("world").getPVP();
    }

    public void setDifficulty(Difficulty difficulty) {
        for (World w : plugin.getServer().getWorlds()) {
            if (w != null) {
                w.setDifficulty(difficulty);
            }
        }
    }

    public Difficulty getDifficulty() {
        return Bukkit.getWorld("world").getDifficulty();
    }

    public void setKeepInventory(Boolean value) {
        for (World w : plugin.getServer().getWorlds()) {
            if (w != null) {
                w.setGameRule(GameRule.KEEP_INVENTORY, value);
            }
        }
    }

    public boolean getKeepInventory() {
        return Bukkit.getWorld("world").getGameRuleValue(GameRule.KEEP_INVENTORY);
    }
    public void setNaturalRegeneration(Boolean value) {
        for (World w : plugin.getServer().getWorlds()) {
            if (w != null) {
                w.setGameRule(GameRule.NATURAL_REGENERATION, value);
            }
        }
    }

    public boolean getNaturalRegeneration() {
        return Bukkit.getWorld("world").getGameRuleValue(GameRule.NATURAL_REGENERATION);
    }

    public Timer getTimer() {
        return timer;
    }

    public VanishUtils getVanish() {
        return vanish;
    }

    public boolean isWaitingForShutdown() {
        return waitingForShutdown;
    }

    public void setWaitingForShutdown(boolean waitingForShutdown) {
        this.waitingForShutdown = waitingForShutdown;
    }

    public BackpackGui getBackpack() {
        return backpack;
    }

    public File getBackpackConfigFile() {
        return backpackConfigFile;
    }

    public ScoreManager getScoreManager() {
        return scoreManager;
    }

    public NMSUtils getNMSUtils() {
        return nmsUtils;
    }

    public File getAllItemsConfigFile() {
        return AllItemsConfigFile;
    }

    public ServerType getServerType() {
        return serverType;
    }

    public String getPREFIX() {
        return PREFIX;
    }

    public String getGUIPREFIX() {
        return GUIPREFIX;
    }

    public int getProtocolVersion() {
        return protocolVersion;
    }

    public ArrayList<Material> getNotAvailableMaterials() {
        return not_available_materials;
    }

    public ArrayList<Material> getMaterials() {
        return materials;
    }
}