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

#include <QEventLoop>

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


WinConsole::WinConsole(QObject* parento) : QObject(parento)
{
    _setmode(_fileno(stdout), _O_U16TEXT);
}

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();
}
