#include <Ogre.h>
#include <OgrePage.h>
#include <OgrePageManager.h>
#include <OgrePagedWorld.h>
#include <OgrePagedWorldSection.h>
#include <chrono>
#include <future>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <thread>

namespace {
void require(bool condition, const char* message) {
    if (!condition)
        throw std::runtime_error(message);
}

class TraceProvider final : public Ogre::PageProvider {
public:
    bool prepareProceduralPage(Ogre::Page* page, Ogre::PagedWorldSection*) override {
        require(std::this_thread::get_id() != mainThread_, "prepare must run on worker");
        std::cout << "page.prepare worker id=" << page->getID() << '\n';
        if (page->getID() == 3)
            OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "fixture preparation failed");
        return true;
    }

    bool loadProceduralPage(Ogre::Page* page, Ogre::PagedWorldSection*) override {
        require(std::this_thread::get_id() == mainThread_, "load must run on main thread");
        std::cout << "page.load main id=" << page->getID() << '\n';
        loaded = page->getID();
        return true;
    }

    Ogre::PageID loaded = 0;

private:
    const std::thread::id mainThread_ = std::this_thread::get_id();
};

void waitForSingleWorker(Ogre::WorkQueue& queue) {
    auto marker = std::make_shared<std::promise<void>>();
    auto ready = marker->get_future();
    queue.addTask([marker] { marker->set_value(); });
    using namespace std::chrono_literals;
    require(ready.wait_for(5s) == std::future_status::ready, "worker marker timed out");
}

void run(const char* renderPlugin) {
    static_assert(OGRE_VERSION == 919043 && OGRE_THREAD_SUPPORT == 3);
    Ogre::Root root("", "", "depth-paging-ogre.log");
    auto& queue = *root.getWorkQueue();
    queue.setWorkerThreadCount(1);
    root.loadPlugin(renderPlugin);
    auto* backend = root.getRenderSystemByName("Tiny Rendering Subsystem");
    require(backend, "expected Tiny Rendering Subsystem");
    root.setRenderSystem(backend);
    root.initialise(false);
    root.createRenderWindow("depth-paging", 32, 32, false);
    auto* scene = root.createSceneManager();

    TraceProvider provider;
    Ogre::PageManager manager;
    manager.setPageProvider(&provider);
    auto* world = manager.createWorld("DepthWorld");
    auto* section = world->createSection("Grid2D", scene, "DepthSection");
    for (const Ogre::PageID id : {1, 2, 3}) {
        provider.loaded = 0;
        section->loadPage(id);
        auto* page = section->getPage(id);
        require(page, "section did not keep a page instance");
        waitForSingleWorker(queue);
        require(provider.loaded == 0, "unexpected final load before main-thread pump");
        if (id == 2)
            page->unload();
        queue.processMainThreadTasks();
        require(provider.loaded == (id == 1 ? id : 0), "wrong page completion branch");
        section->unloadPage(id);
        require(!section->getPage(id), "page still registered after removal");
        std::cout << "page.result id=" << id << " loaded=" << (provider.loaded != 0)
                  << " removed=1\n";
    }
    manager.destroyWorld(world);
}
} // namespace

int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "Usage: depth-paging /absolute/path/to/RenderSystem_Tiny\n";
        return 2;
    }
    try {
        run(argv[1]);
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        return 1;
    }
}
