package com.bitnix.dirtguilds;

import com.bitnix.dirtguilds.command.DirtGuildsCommand;
import com.bitnix.dirtguilds.data.DatabaseManager;
import com.bitnix.dirtguilds.guild.GuildManager;
import com.bitnix.dirtguilds.hook.EconomyHook;
import com.bitnix.dirtguilds.listener.ChatListener;
import com.bitnix.dirtguilds.listener.GuildFriendlyFireListener;
import com.bitnix.dirtguilds.listener.GuiListener;
import com.bitnix.dirtguilds.util.MessageUtil;
import org.bukkit.plugin.java.JavaPlugin;

public class DirtGuildsPlugin extends JavaPlugin {

    private DatabaseManager databaseManager;
    private GuildManager guildManager;
    private MessageUtil messageUtil;
    private EconomyHook economyHook;

    @Override
    public void onEnable() {
        saveDefaultConfig();

        this.messageUtil = new MessageUtil(this);

        this.economyHook = new EconomyHook(this);
        boolean economyEnabled = this.economyHook.setup();
        if (economyEnabled) {
            getLogger().info("Vault economy hooked successfully.");
        } else {
            getLogger().warning("Vault economy not found. Guild bank will run in internal-only mode.");
        }

        this.databaseManager = new DatabaseManager(this);
        this.databaseManager.initialize();

        this.guildManager = new GuildManager(this, this.databaseManager);
        this.guildManager.loadAll();

        DirtGuildsCommand command = new DirtGuildsCommand(this);
        if (getCommand("dirtguilds") != null) {
            getCommand("dirtguilds").setExecutor(command);
            getCommand("dirtguilds").setTabCompleter(command);
        }

        getServer().getPluginManager().registerEvents(new GuiListener(this), this);
        getServer().getPluginManager().registerEvents(new ChatListener(this), this);
        getServer().getPluginManager().registerEvents(new GuildFriendlyFireListener(this), this);

        getLogger().info("DirtGuilds enabled.");
    }

    @Override
    public void onDisable() {
        getServer().getScheduler().cancelTasks(this);

        if (guildManager != null) {
            guildManager.shutdown();
        }

        if (databaseManager != null) {
            databaseManager.close();
        }

        getLogger().info("DirtGuilds disabled.");
    }

    public DatabaseManager getDatabaseManager() {
        return databaseManager;
    }

    public GuildManager getGuildManager() {
        return guildManager;
    }

    public MessageUtil getMessageUtil() {
        return messageUtil;
    }

    public EconomyHook getEconomyHook() {
        return economyHook;
    }
}
