#include "fgc/ui/HeadlessUi.h"

#include <chrono>
#include <iostream>
#include <string>

namespace fgc {

HeadlessUi::~HeadlessUi() { stop(); }

void HeadlessUi::start(SnapshotFn /*snapshot*/, CommandSink sink) {
    sink_ = std::move(sink);
    running_ = true;
    input_thread_ = std::thread(&HeadlessUi::inputLoop, this);
}

void HeadlessUi::stop() {
    if (!running_.exchange(false)) return;
    // inputLoop blocks on getline; closing happens when stdin hits EOF or the
    // process exits. Detach if it is still parked so shutdown does not hang.
    if (input_thread_.joinable()) {
        if (std::cin.eof()) input_thread_.join();
        else                input_thread_.detach();
    }
}

// Lifted verbatim from the old Application::Impl::inputLoop: read lines and push
// them onto the command sink (formerly the cmd_queue).
void HeadlessUi::inputLoop() {
    std::string line;
    while (running_) {
        if (!std::getline(std::cin, line)) {
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
            continue;
        }
        if (line.empty()) continue;
        if (sink_) sink_(line);
    }
}

}  // namespace fgc
