package io.papermc.paper.plugin;

import com.mojang.logging.LogUtils;
import joptsimple.OptionSet;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class PluginInitializerManager {

    private static final Logger LOGGER = LogUtils.getLogger();
    private static PluginInitializerManager impl;
    private final Path pluginDirectory;
    private final Path updateDirectory;

    PluginInitializerManager(@NotNull OptionSet minecraftOptionSet) {
        // We have to load the bukkit configuration inorder to get the update folder location.
        File configFileLocationBukkit = (File) minecraftOptionSet.valueOf("bukkit-settings");
        this.pluginDirectory = ((File) minecraftOptionSet.valueOf("plugins")).toPath();

        String updateDirectory = YamlConfiguration.loadConfiguration(configFileLocationBukkit).getString("settings.update-folder", "update");
        if (updateDirectory.isBlank()) {
            this.updateDirectory = null;
        } else {
            Path resolvedUpdateDirectory = this.pluginDirectory.resolve(updateDirectory);
            if (!Files.isDirectory(resolvedUpdateDirectory)) {
                this.updateDirectory = null;
                return;
            }

            boolean isSameFile = true;
            try {
                isSameFile = Files.isSameFile(resolvedUpdateDirectory, this.pluginDirectory);
            } catch (IOException e) {
                LOGGER.error("Misconfigured update directory!");
                LOGGER.error("Failed to compare update/plugin directory", e);
            }

            if (isSameFile) {
                LOGGER.error("Misconfigured update directory!");
                LOGGER.error(("Your configured update directory (%s) in bukkit.yml is pointing to the same location as the plugin directory (%s). " +
                    "Disabling auto updating functionality.").formatted(resolvedUpdateDirectory, this.pluginDirectory));

                this.updateDirectory = null;
            } else {
                this.updateDirectory = resolvedUpdateDirectory;
            }

        }

    }

    public static PluginInitializerManager init(OptionSet optionSet) {
        impl = new PluginInitializerManager(optionSet);
        return impl;
    }

    public static PluginInitializerManager instance() {
        return impl;
    }

    @NotNull
    public Path pluginDirectoryPath() {
        return pluginDirectory;
    }

    @Nullable
    public Path pluginUpdatePath() {
        return updateDirectory;
    }

}
