package hu.jgj52.pvpcore.Utils;

import org.bukkit.*;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import java.io.File;

public class WorldReset {
    private Plugin plugin;

    public WorldReset(Plugin plugin) {
        this.plugin = plugin;
    }

    public final String[] metadatas = {"DuelingWith", "ArenaLoc", "Frozen", "DuelRequest", "DueledBy", "DueledWithGamemode", "IsSpectating"};

    public boolean recreateArenaWorld() {
        String worldName = "arenas";

        try {
            removeArenaWorld(worldName);

            Bukkit.getScheduler().runTaskLater(plugin, () -> {
                createArenaWorld(worldName);
            }, 20L);

            return true;

        } catch (Exception e) {
            plugin.getLogger().severe("Error recreating arena world: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    private boolean removeArenaWorld(String worldName) {
        try {
            World world = Bukkit.getWorld(worldName);

            if (world != null) {

                world.getPlayers().forEach(player -> {
                    Location spawn = new Location(Bukkit.getWorld("world"), 0, 3, 0, 0, 0);
                    for (PotionEffect potionEffect : player.getActivePotionEffects()) {
                        player.removePotionEffect(potionEffect.getType());
                    }
                    player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 20, 1), true);
                    player.setHealth(20D);
                    player.setFoodLevel(20);
                    player.setSaturation(5);
                    player.setGameMode(GameMode.ADVENTURE);
                    player.teleport(spawn);
                    for (String key : metadatas) {
                        for (MetadataValue value : player.getMetadata(key)) {
                            if (value.getOwningPlugin() == plugin) {
                                player.removeMetadata(key, plugin);
                                break;
                            }
                        }
                    }
                    player.sendMessage("§cszia resetel a map szoval tunes");
                });

                boolean unloaded = Bukkit.unloadWorld(world, false);

                if (unloaded) {
                    File worldFolder = new File(Bukkit.getWorldContainer(), worldName);
                    if (worldFolder.exists()) {
                        deleteDirectory(worldFolder);
                    }

                    return true;
                } else {
                    plugin.getLogger().warning("Failed to unload arena world.");
                    return false;
                }
            } else {
                return true;
            }
        } catch (Exception e) {
            plugin.getLogger().severe("Error removing arena world: " + e.getMessage());
            return false;
        }
    }

    private boolean createArenaWorld(String worldName) {
        try {
            WorldCreator creator = new WorldCreator(worldName)
                    .type(WorldType.FLAT)
                    .environment(World.Environment.NORMAL)
                    .generateStructures(false)
                    .generatorSettings("{\"layers\":[{\"block\":\"air\",\"height\":1}],\"biome\":\"plains\"}");

            World world = creator.createWorld();

            if (world != null) {
                world.setSpawnFlags(false, false);
                world.setTime(6000);
                world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false);
                world.setStorm(false);
                world.setThundering(false);
                world.setGameRule(GameRule.DO_WEATHER_CYCLE, false);
                return true;
            } else {
                plugin.getLogger().severe("Failed to create arena world!");
                return false;
            }

        } catch (Exception e) {
            plugin.getLogger().severe("Error creating arena world: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    private boolean deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
        }
        return directory.delete();
    }
}