#include "consolelistener.h"
#include <iostream>

ConsoleListener::ConsoleListener(QObject *parent) : QObject(parent) {
    QObject::connect(this, &ConsoleListener::finished_getline, this, [this](QString const& str) {
        emit newline(str);
    }, Qt::QueuedConnection);
    m_notifier->moveToThread(&m_thread);
    QObject::connect(&m_thread, &QThread::finished, m_notifier, &QObject::deleteLater);
#ifdef Q_OS_WIN
    QObject::connect(m_notifier, &QWinEventNotifier::activated, [this]() {
        std::string line;
        std::getline(std::cin, line);
        emit finished_getline(QString::fromStdString(line));
    });
#else
    QObject::connect(m_notifier, &QSocketNotifier::activated, [this]() {
        std::string line;
        std::getline(std::cin, line);
        emit finished_getline(QString::fromStdString(line));
    });
#endif
    m_thread.start();
}

ConsoleListener::~ConsoleListener() {
    m_thread.quit();
    m_thread.wait();
}
