#include <QtWidgets>

#include "mainwindow.hpp"

MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {
  setWindowTitle(tr("ololo"));
  setGeometry(100, 100, 300, 200);

  // widgets
  button = new QPushButton(tr("Push Me!"));
  textBrowser = new QTextBrowser();

  // layout
  QGridLayout *mainLayout = new QGridLayout;
  mainLayout->addWidget(button, 0, 0);
  mainLayout->addWidget(textBrowser, 1, 0);
  setLayout(mainLayout);

  // signals
  connect(button, SIGNAL(released()), this, SLOT(onButtonReleased()));
  connect(&process, SIGNAL(readyReadStandardOutput()), this, SLOT(onCaptureProcessOutput()));
}

MainWindow::~MainWindow() {
  delete button;
  delete textBrowser;
}

void MainWindow::onButtonReleased() {
  textBrowser->clear();
  textBrowser->append(tr("Running command:\n"));

  process.setCurrentWriteChannel(QProcess::StandardOutput);

  process.start("ls", QStringList() << "-lh" << qgetenv("HOME"));
  // if (!process.waitForStarted() || !process.waitForFinished()) {
  //   return;
  // }
}

void MainWindow::onCaptureProcessOutput() {
  QProcess *proc = qobject_cast<QProcess *>(sender());

  if (proc) {
    textBrowser->append(proc->readAllStandardOutput());
  }
}
