package me.nvus.nvus_prison_setup;

import me.nvus.nvus_prison_setup.Configs.ConfigManager;
import me.nvus.nvus_prison_setup.Listeners.*;
import me.nvus.nvus_prison_setup.Configs.SettingsMenu;
import me.nvus.nvus_prison_setup.Updater.UpdateChecker;
import me.nvus.nvus_prison_setup.Listeners.ToolDamageListener;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public final class PrisonSetup extends JavaPlugin {

    private ConfigManager configManager;

    @Override
    public void onEnable() {
        // Initialize the ConfigManager
        configManager = new ConfigManager(this);

        // Save the default configs, if they doesn't exist
        configManager.saveDefaultConfig("config.yml");
        configManager.saveDefaultConfig("banned_items.yml");
        configManager.saveDefaultConfig("auto_switch.yml");

        // Update config file(s) when new updates come out and they need replaced
        checkAndUpdateConfigs();

        // Register event listeners
        getServer().getPluginManager().registerEvents(new PlayerSpawn(configManager), this);
        getServer().getPluginManager().registerEvents(new PlayerArmor(configManager), this);
        getServer().getPluginManager().registerEvents(new PlayerItems(configManager), this);
        getServer().getPluginManager().registerEvents(new BlockListener(this), this);
        getServer().getPluginManager().registerEvents(new ToolSwitchListener(configManager), this);
        this.getCommand("nvus").setExecutor(new CommandListener(this, configManager));
        //new SettingsMenu(this, configManager);
        getServer().getPluginManager().registerEvents(new SettingsMenu(this, configManager), this);

        // Tool Damage
        ToolDamageListener toolDamageListener = new ToolDamageListener(configManager);
        getServer().getPluginManager().registerEvents(toolDamageListener, this);

        getLogger().info(ChatColor.translateAlternateColorCodes('&',"&a&lNVus Prison Setup has been successfully enabled!"));

        new UpdateChecker(this, 12345).getVersion(version -> {
            if (!this.getDescription().getVersion().equals(version)) {
                getLogger().info("There is a new update available for NVus Prison Setup! Grab it from SpigotMC here: https://www.spigotmc.org/resources/nvus-prison-setup.115441/");

                Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
                    for (Player player : Bukkit.getOnlinePlayers()) {
                        if (player.isOp() || player.hasPermission("nvus.admin")) {
                            player.sendMessage(ChatColor.RED + "=====================================================");
                            player.sendMessage(ChatColor.YELLOW + "An update for NVus Prison Setup is available! Grab it from SpigotMC here: https://www.spigotmc.org/resources/nvus-prison-setup.115441/");
                            player.sendMessage(ChatColor.RED + "=====================================================");
                        }
                    }
                }, 20L * 60);
            }
        });

    }


    @Override
    public void onDisable() {
        // Save the config when disabling the plugin
        configManager.saveConfig("config.yml");
        configManager.saveConfig("banned_items.yml");
        configManager.saveConfig("auto_switch.yml");

        // Log a success message
        getLogger().info(ChatColor.translateAlternateColorCodes('&',"&c&lNVus Prison Setup has been successfully disabled!"));
    }

    public ConfigManager getConfigManager() {
        return configManager;
    }

    private void checkAndUpdateConfigs() {
        File configFile = new File(getDataFolder(), "config.yml");
        if (!configFile.exists()) {
            saveResource("config.yml", false);
            saveResource("auto_switch.yml", false);
            return;
        }

        FileConfiguration config = YamlConfiguration.loadConfiguration(configFile);
        String configVersion = config.getString("ConfigVersion", "0"); // Default to "0" if not found
        if (!"1.0".equals(configVersion)) {
            backupAndReplaceConfig("config.yml");
            backupAndReplaceConfig("auto_switch.yml");

            // After backing up and copying new ones, you might want to reload these configs into your ConfigManager
            // assuming you have such a method in your ConfigManager
            getConfigManager().reloadConfig("config.yml");
            getConfigManager().reloadConfig("auto_switch.yml");
        }
    }

    private void backupAndReplaceConfig(String fileName) {
        File configFile = new File(getDataFolder(), fileName);
        File backupFile = new File(getDataFolder(), fileName + ".BACKUP");

        // Backup the old file
        try {
            Files.move(configFile.toPath(), backupFile.toPath());
        } catch (IOException e) {
            getLogger().warning("Could not backup " + fileName + ": " + e.getMessage());
        }

        // Copy new file from resources
        saveResource(fileName, false);
    }


}
