// SPDX-FileCopyrightText: 2021 - 2026 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#ifndef LIFECYCLE_H
#define LIFECYCLE_H

#include <dfm-framework/lifecycle/pluginmetaobject.h>
#include <dfm-framework/lifecycle/plugin.h>
#include <dfm-framework/lifecycle/plugincreator.h>
#include <dfm-framework/dfm_framework_global.h>

#include <QString>
#include <QObject>

#include <atomic>
#include <functional>

DPF_BEGIN_NAMESPACE

namespace LifeCycle {
// Cross-TU shutdown flag set by shutdownPlugins() before any plugin stop().
// Used by framework hot paths (e.g. EventChannel) and plugin destructors to
// short-circuit cross-plugin calls during atexit, where Q_GLOBAL_STATIC
// destruction order is undefined and may produce use-after-free.
//
// NOTE: do NOT rely on QCoreApplication::closingDown() — when the host exits
// via exit() (e.g. X11 IO error path), the stack-allocated QApplication does
// not unwind and closingDown() remains false.
extern std::atomic<bool> g_shuttingDown;
inline bool isShuttingDown() noexcept
{
    return g_shuttingDown.load(std::memory_order_acquire);
}

void initialize(const QStringList &IIDs, const QStringList &paths);
void initialize(const QStringList &IIDs, const QStringList &paths, const QStringList &blackNames);
void initialize(const QStringList &IIDs, const QStringList &paths, const QStringList &blackNames,
                const QStringList &lazyNames);
void registerQtVersionInsensitivePlugins(const QStringList &names);

bool isAllPluginsInitialized();
bool isAllPluginsStarted();
QStringList pluginIIDs();
QStringList pluginPaths();
QStringList blackList();
QStringList lazyLoadList();
PluginMetaObjectPointer pluginMetaObj(const QString &pluginName,
                                      const QString version = "");
QList<PluginMetaObjectPointer> pluginMetaObjs(const std::function<bool(PluginMetaObjectPointer)> &cond = {});
QList<PluginMetaObjectPointer> pluginSortedMetaObjs(const std::function<bool(PluginMetaObjectPointer)> &cond = {});

bool readPlugins();
bool loadPlugins();
void shutdownPlugins();

bool loadPlugin(PluginMetaObjectPointer &pointer);
void shutdownPlugin(PluginMetaObjectPointer &pointer);

void setLazyloadFilter(std::function<bool(const QString &)> filter);
void setBlackListFilter(std::function<bool(const QString &)> filter);
}   // namepsace LifeCycle

DPF_END_NAMESPACE

#endif   // LIFECYCLE_H
