#include "LogViewer.h"
#include <errno.h>
#include <QString>
#include <QChar>
#include <QPlainTextEdit>
#include <QTextCursor>

LogViewer::LogViewer(QPlainTextEdit * init_edit) : edit(init_edit) {
   return;
}

void
LogViewer::LogRead(ssize_t rval, const void * buf, size_t count) {
   LogIO('R', rval, buf, count);
}

void
LogViewer::LogWrite(ssize_t rval, const void * buf, size_t count) {
   LogIO('W', rval, buf, count);
}

void
LogViewer::LogIO(char prfx, ssize_t rval, const void * buf, size_t /* count */) {
   int save_err = errno;
   QString line;
   line.append(QChar(prfx));
   line.append(":");
   if (rval < 0) {
      line.append(QString(" rval = %1, errno = %2 (%3)")
                  .arg(rval).arg(save_err).arg(QString(strerror(save_err))));
   } else if (rval == 0) {
      line.append(" zero length I/O");
   } else {
      const unsigned char * bp = (const unsigned char *)buf;
      while (rval-- > 0) {
         line.append(QString(" %1").arg(*bp++,2,16,QChar('0')));
      }
   }
   line.append("\n");
   edit->moveCursor(QTextCursor::End);
   edit->textCursor().insertText(line);
   errno = save_err;
}
