/*
 * MIT License
 * Author: Mark Allyn
 *
 * scope_manager.cpp
 */

#include "scope_manager.h"
#include <GLFW/glfw3.h>
#include <cstdio>

void ScopeManager::addScope(std::unique_ptr<Scope> scope) {
    scopes_.push_back(std::move(scope));
}

bool ScopeManager::init(const std::string& shaderDir) {
    for (auto& s : scopes_) {
        if (!s->init(shaderDir)) {
            fprintf(stderr, "ScopeManager: init failed for %s\n",
                    s->getName().c_str());
            return false;
        }
    }
    return true;
}

void ScopeManager::render(float dt, float viewportW, float viewportH) {
    if (scopes_.empty()) return;

    Scope* s = scopes_[current_].get();
    s->tickTimer(dt);

    if (s->shouldAdvance())
        advanceScope(+1);

    scopes_[current_]->render(dt, viewportW, viewportH);
}

void ScopeManager::handleKey(int key, int scancode, int action, int mods) {
    if (scopes_.empty()) return;

    // s / S are consumed here — scope classes never see them
    if (action == GLFW_PRESS || action == GLFW_REPEAT) {
        if (key == GLFW_KEY_S) {
            if (mods & GLFW_MOD_SHIFT)
                advanceScope(-1);
            else
                advanceScope(+1);
            return;
        }
    }

    // Any key resets the timer
    if (action == GLFW_PRESS)
        scopes_[current_]->resetTimer();

    scopes_[current_]->handleKey(key, scancode, action, mods);
}

void ScopeManager::advanceScope(int direction) {
    if (scopes_.empty()) return;
    int n = static_cast<int>(scopes_.size());
    current_ = (current_ + direction + n) % n;
    scopes_[current_]->resetTimer();
}
