/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include "core_bindings.h"
#include "core_utils.h"
#include "qt_bindings.h"
#include "docstrings.h"

#include <Core.h>
#include <Application.h>
#include <ExtensionManager.h>
#include <MainWindow.h>
#include <Action.h>
#include <Component.h>
#include <Viewer.h>
#include <TransformationManager.h>
#include <PythonManager.h>
#include <InteractiveViewer.h>
#include <Log.h>

#include <thread>
#include <chrono>

namespace camitk {

void refresh() {
    TransformationManager::cleanupFramesAndTransformations();
    Application::refresh();
}

void startApplication() {
    Log::getLogger()->setLogLevel(InterfaceLogger::INFO);
    Log::getLogger()->setMessageBoxLevel(InterfaceLogger::WARNING); // FIXME Cannot display widget, no event loop
    Log::getLogger()->setDebugInformation(true);

    int argc = 1;
    char* argv = (char*)"camitk-python-application";

    Application* a = new Application("Default Python Application", argc, &argv, false, false);

    // force no redirection to console (to see error message if they occur)
    a->getMainWindow()->redirectToConsole(false);

    ExtensionManager::autoload();

    Viewer* medicalImageViewer = Application::getViewer("Medical Image Viewer");
    if (medicalImageViewer != nullptr) {
        // add the default axial viewer to the default main window
        a->getMainWindow()->setCentralViewer(medicalImageViewer);
        a->getMainWindow()->show();
    }
    else {
        CAMITK_INFO_ALT("No viewer found");
    }
}

void applicationExec() {
    // Start periodic event processing (non-blocking)
    std::thread([&]() {
        while (true) {
            if (Application::instance()) {
                Application::processEvents();  // Process events without blocking
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(10));  // 10ms interval
        }
    }).detach();
}

void showMainWindow() {
    startApplication();
    Application::exec();
}

//
// -- action pipeline
//

Component* applyInPipeline(QString actionName, ComponentList inputComponents) {
    camitk::Action* action = camitk::Application::getAction(actionName);
    if (action != nullptr) {
        if (!inputComponents.empty()) {
            action->setInputComponents(inputComponents);
        }

        camitk::Action::ApplyStatus status = action->applyInPipeline();

        if (status == camitk::Action::SUCCESS) {
            ComponentList outputComponents = action->getOutputComponents();

            // get the first top level component created by the action that is not in the input list
            auto it = std::find_if(outputComponents.cbegin(), outputComponents.cend(), [inputComponents](camitk::Component * c) {
                bool topLevel = c->isTopLevel();
                bool notInput = !inputComponents.contains(c);
                return topLevel && notInput;
            });
            if (it != outputComponents.cend()) {
                // reset modification flags on output components to avoid mismatching it for output component when chaining applyAction
                (*it)->setModified(false);
                return (*it);
            }
            else {
                CAMITK_TRACE_ALT(QString("Action %1 produces no output, returning None").arg(action->getName()))
            }
        }
    }
    else {
        CAMITK_INFO_ALT(QString("Cannot find action '%1'. Check the spelling and the availability in the loaded action extensions. Returning None").arg(actionName))
    }
    return nullptr;
}

//
// -- viewer picking
//

// TODO add this as an Application member? Create a PythonApplication with all the binding methods/helpers above including this?

// stores (viewerName, callback_hash) → connection
static QMap<QPair<QString, unsigned long long>, QMetaObject::Connection> viewerConnections;

// connect and returns true if everything went well
bool connectViewerSelectionChanged(const QString& viewerName, py::function callback) {
    camitk::Viewer* viewer = camitk::Application::getViewer(viewerName);
    if (!viewer) {
        throw std::runtime_error("Viewer not found: " + viewerName.toStdString());
    }

    // Connect the Qt signal to the Python callback if not already connected
    QPair<QString, unsigned long long> key = qMakePair(viewerName, static_cast<unsigned long long>(py::hash(callback)));

    // Prevent duplicate connection
    if (viewerConnections.contains(key)) {
        CAMITK_TRACE_ALT(QString("Viewer '%1' already connected to this callback").arg(viewerName));
        return false;
    }

    // Connect the signal to the Python callback
    auto signalConnection = QObject::connect(
                                viewer,
                                QOverload<>::of(&Viewer::selectionChanged),
                                viewer,
    [callback]() {
        py::gil_scoped_acquire gil;
        try {
            callback();
        }
        catch (const py::error_already_set& e) {
            PyErr_Print();
        }
    },
    Qt::QueuedConnection
                            );

    viewerConnections.insert(key, signalConnection);
    return true;
}

inline bool disconnectViewerSelectionChanged(const QString& viewerName, py::function callback) {
    QPair<QString, unsigned long long> key = qMakePair(viewerName, static_cast<unsigned long long>(py::hash(callback)));

    if (!viewerConnections.contains(key)) {
        CAMITK_TRACE_ALT(QString("No connection found for viewer '%1' and given callback").arg(viewerName));
        return false;
    }

    bool ok = QObject::disconnect(viewerConnections.value(key));
    viewerConnections.remove(key);
    return ok;
}

} // namespace camitk

void add_application_bindings(py::module_& m) {

    // --------------- Application ---------------
    // TODO should we simplify all Application actions to remove the .Application. layer?
    // For instance python developers would then use:
    // image = camitk.open("name.mha")
    // instead of:
    // image = camitk.Application.open("name.mha")

    py::class_<camitk::Application> application(m, "Application", DOC(camitk_Application));

    application.def_static("getAction", &camitk::Application::getAction,
                           py::return_value_policy::reference,
                           DOC(camitk_Application_getAction));

    application.def_static("getActions",
    []() {
        // TODO write a type_caster<camitk::ActionList> similar to type_caster<camitk::ComponentList>, see in core_utils
        camitk::ActionList actionList = camitk::Application::getActions();
        std::vector<camitk::Action*> stdActionList(actionList.constBegin(), actionList.constEnd());
        return stdActionList;
    },
    py::return_value_policy::reference,
    DOC(camitk_Application_getActions_1));

    application.def_static("getTopLevelComponents", &camitk::Application::getTopLevelComponents,
                           py::return_value_policy::reference,
                           DOC(camitk_Application_getTopLevelComponents));

    application.def_static("open", &camitk::Application::open,
                           py::return_value_policy::reference,
                           py::arg("fileName"),
                           py::arg("blockRefresh") = false,
                           DOC(camitk_Application_open));

    application.def_static("save", [](camitk::Component * c) {
        // Note: using the action instead of the Application method so that it will be registered
        // in history
        camitk::ComponentList componentToSave({c});
        camitk::applyInPipeline("Save", componentToSave);
    },
    DOC(camitk_Application_save));

    application.def_static("saveAs", [](camitk::Component * c) {
        // Note: using the action instead of the Application method so that it will be registered
        // in history
        camitk::ComponentList componentToSave({c});
        camitk::applyInPipeline("Save As", componentToSave);
    },
    R"doc(Saves the given Component by prompting the user for a file name.
This method uses the 'Save As' Action to save the given Component, which will prompt the user for a file name.)doc");

    application.def_static("close", [](camitk::Component & c, bool forceClose) {
        // if forceClose is true, the modified flag is reset so that the user is not asked to save
        if (forceClose) {
            c.setModified(false);
        }
        camitk::Application::close(&c, true);
    },
    DOC(camitk_Application_close));

    application.def_static("closeAll",
    []() {
        return (camitk::Application::getAction("Close All")->apply() == camitk::Action::SUCCESS);
    },
    R"doc(Closes all opened Components, prompting the user to save modified ones.
This method uses the 'Close All' Action to close all opened Components.)doc");

    // as the isAlive method is overloaded, we must be explicit to define
    // which one is to be called.
    // see https://pybind11.readthedocs.io/en/stable/classes.html#overloaded-methods
    // + as the user should be able to send a None/nullptr instead of a
    // valid pointer as the parameter, we must add a specific param name and set
    // its `none(...)` flag to true
    // see https://pybind11.readthedocs.io/en/stable/advanced/functions.html#allow-prohibiting-none-arguments
    // for `static bool isAlive(Component*)`
    application.def_static("isAlive",
                           py::overload_cast<camitk::Component*>(&camitk::Application::isAlive),
                           py::arg("component").none(true),
                           DOC(camitk_Application_isAlive_1));

    // for `static bool isAlive(Action*)`
    application.def_static("isAlive",
                           py::overload_cast<camitk::Action*>(&camitk::Application::isAlive),
                           py::arg("action").none(true),
                           DOC(camitk_Application_isAlive_2));

    application.def_static("applyAction", [](QString & name) -> camitk::Component* {
        return applyInPipeline(name, camitk::ComponentList());
    },
    py::return_value_policy::reference,
    R"doc(Applies the action of the given name and returns the top-level output Component created by it if any or None if there is no output component. The given action must require no input component)doc");

    application.def_static("applyAction", [](QString & name, camitk::Component & targetComp) -> camitk::Component* {
        camitk::ComponentList inputComponents;
        inputComponents.append(&targetComp);
        return applyInPipeline(name, inputComponents);
    },
    py::return_value_policy::reference,
    R"doc(Applies the action of the given name that takes the given component as input and returns the top-level output Component created by it if any or None if there is no output component. The given action must require one and only one input component)doc");

    application.def_static("applyAction", [](QString & name, camitk::ComponentList & targetList) -> camitk::Component* {
        return applyInPipeline(name, targetList);
    },
    py::return_value_policy::reference,
    R"doc(Applies the action of the given name that takes the given list of components as input and returns the top-level output Component created by it if any or None if there is no output component. The given action must require a list of input components)doc");

    application.def_static("connectViewerSelectionChanged", &camitk::connectViewerSelectionChanged,
                           py::arg("viewerName"),
                           py::arg("callback"),
                           R"doc(Connects a Python callback to a Viewer's selectionChanged() signal by name (if not already connected).)doc");

    application.def_static("disconnectViewerSelectionChanged", &camitk::disconnectViewerSelectionChanged,
                           py::arg("viewerName"),
                           py::arg("callback"),
                           "Disconnects a Python callback from a Viewer's selectionChanged() signal by name (if already connected).");

    application.def_static("update3DClippingPlanes", []() {
        camitk::InteractiveViewer* default3DViewer = dynamic_cast<camitk::InteractiveViewer*>(camitk::Application::getViewer("3D Viewer"));

        if (default3DViewer != nullptr) {
            default3DViewer->getRendererWidget()->resetClippingPlanes();
        }
    },
    R"doc(Updates the clipping planes of the default 3D Viewer.
    This might be required when the working space volume changes rapidly, for instance in navigation system where the tracker moves some mesh in real 3D space or for RV application).)doc");

    // --------------- Utils ---------------
    // util functions directly linked to the Application class

    m.def("startApplication", &camitk::startApplication,
          R"doc(Starts a default CamiTK Application with the default main window and event loop.
          This function is experimental and is still not entirely functional nor stable.
          Use at your own risks and only if you know what your doing.
          
          You have been warned!)doc");

    m.def("show", &camitk::showMainWindow,
          R"doc(Starts a default CamiTK Application with the default main window and event loop, and shows the main window.
          This function is experimental and is still not entirely functional nor stable.
          Use at your own risks and only if you know what your doing.
          
          You have been warned!)doc");

    m.def("refresh", &camitk::refresh,
          R"doc(Refreshes the application, including the transformation manager and all registered viewers.)doc");
}

