/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License v2 as published by the
 * Free Software Foundation.
 */

#include "Config.h"
#include "EncounterJournalMgr.h"
#include "Log.h"
#include "ScriptMgr.h"

void AddSC_encounter_journal_commands();

class encounter_journal_world_script : public WorldScript
{
public:
    encounter_journal_world_script()
        : WorldScript("encounter_journal_world_script",
            { WORLDHOOK_ON_LOAD_CUSTOM_DATABASE_TABLE })
    { }

    void OnLoadCustomDatabaseTable() override
    {
        if (!sConfigMgr->GetOption<bool>("EncounterJournal.Enable", true))
        {
            LOG_INFO("server.loading", ">> mod-encounter-journal disabled "
                "via EncounterJournal.Enable=0.");
            return;
        }

        sEncounterJournalMgr->Load();

        if (sConfigMgr->GetOption<bool>("EncounterJournal.ImportOnStart", false))
        {
            MoonWell::EncounterJournal::Mgr::SkeletonCounts sc;
            std::vector<std::string> warnings;
            std::size_t inserted =
                sEncounterJournalMgr->ImportSkeleton(sc, warnings);
            LOG_INFO("server.loading",
                ">> mod-encounter-journal: ImportOnStart added {} skeleton rows "
                "(tiers={}, instances={}, encounters={}, creatures={}, sections={}).",
                inserted, sc.tiers, sc.instances, sc.encounters,
                sc.creatures, sc.sections);

            std::vector<std::string> lootWarn;
            std::size_t lootRows = sEncounterJournalMgr->ImportLoot(lootWarn);
            LOG_INFO("server.loading",
                ">> mod-encounter-journal: ImportOnStart added {} loot rows.",
                lootRows);

            sEncounterJournalMgr->Load();
        }

        if (!sConfigMgr->GetOption<bool>("EncounterJournal.ExportOnStart", false))
            return;

        std::vector<std::string> paths;
        std::string error;
        if (!sEncounterJournalMgr->Export(paths, error))
        {
            LOG_ERROR("server.loading",
                ">> mod-encounter-journal: ExportOnStart failed: {}", error);
            return;
        }

        for (std::string const& p : paths)
            LOG_INFO("server.loading",
                ">> mod-encounter-journal: wrote {}", p);
    }
};

void Addmod_encounter_journalScripts()
{
    if (!sConfigMgr->GetOption<bool>("EncounterJournal.Enable", true))
        return;

    new encounter_journal_world_script();
    AddSC_encounter_journal_commands();
    LOG_INFO("server.loading",
        ">> mod-encounter-journal scripts registered (.ej commands available).");
}
