/**
 * Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
 * Copyright (C) 2012-2023 Arm Limited (or its affiliates).
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */

#include <stdlib.h>
#include "terminal.h"
#include "terminalutil.h"

void Terminal::setWindowSize(int cols, int rows)
{
    mRows = rows;
    mColumns = cols;
    emit windowSizeChanged(mColumns, mRows);
    winch();
}

int Terminal::rows() const
{
    return mRows;
}

int Terminal::columns() const
{
    return mColumns;
}

void Terminal::emitProcessStarted(const QString& commandLine)
{
    emit processStarted(commandLine);
}

void Terminal::emitProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    emit processFinished(exitCode, exitStatus);
}

void Terminal::pushBytes(const QByteArray& ba)
{
    mPushedBytes.append(ba);
    emit readyRead();
}

qint64 Terminal::readData(char * data, qint64 maxSize)
{
    if (!mPushedBytes.isEmpty())
        return mPushedBytes.readData(data, maxSize);
    else
#ifdef Q_OS_WIN
        return 0;
#else
        return QLocalSocket::readData(data, maxSize);
#endif
}

void Terminal::setProcess(QProcess *process)
{
    mCurrentProcess = process;
}

qint64 Terminal::bytesAvailable() const
{
    return mPushedBytes.size() + QIODevice::bytesAvailable();
}

bool Terminal::atEnd() const
{
    return mPushedBytes.isEmpty() && QIODevice::atEnd();
}

bool Terminal::isSequential() const
{
    return true;
}
