/***************************************************************************
 *   Copyright (C) 2004-2024 by Pere Constans
 *   constans@molspaces.com
 *   cb2Bib version 2.0.2. Licensed under the GNU GPL version 3.
 *   See the LICENSE file that comes with this distribution.
 ***************************************************************************/
#include "WinConsole.h"

#include <QEventLoop>
#include <QSysInfo>

#include <fcntl.h>
#include <io.h>
#include <iostream>


WinConsole::WinConsole(QObject* parento) : QObject(parento)
{
    // Exclude _setmode on older Windows consoles
    if (int(QSysInfo::productVersion().toDouble()) > 7)
    {
        try
        {
            fflush(stdout);
            _setmode(_fileno(stdout), _O_U16TEXT);
        }
        catch (...)
        {
            fflush(stdout);
            _setmode(_fileno(stdout), _O_TEXT);
        }
    }
}

WinConsole::~WinConsole() {}


int WinConsole::execute(const QString& program, const QStringList& arguments)
{
    QEventLoop eventloop(this);
    _process.setProcessChannelMode(QProcess::MergedChannels);

    connect(&_process, SIGNAL(readyReadStandardOutput()), this, SLOT(output()));
    connect(&_process, SIGNAL(finished(int,QProcess::ExitStatus)), &eventloop, SLOT(quit()));

    _process.start(program, arguments);
    if (_process.waitForStarted())
        eventloop.exec();
    output();
    std::wcout << std::endl;

    return _process.exitCode();
}

void WinConsole::output()
{
    while (_process.canReadLine())
        std::wcout << QString::fromUtf8(_process.readLine()).toStdWString();
}
