/**
 *
 * @copyright Copyright (c) 2018-2021, ownCloud GmbH
 * @license OCL
 * @author Christian Kamm mail@ckamm.de
 * @author Hannah von Reth hannah.vonreth@owncloud.com
 *
 * This code is covered by the ownCloud Commercial License.
 *
 * You should have received a copy of the ownCloud Commercial License
 * along with this program. If not, see <https://owncloud.com/licenses/owncloud-commercial/>.
 *
 */

#include "validationdevice.h"
#include "common/utility.h"

namespace OCC {

qint64 PlaceholderValidationDevice::size() const
{
    return _size;
}

qint64 PlaceholderValidationDevice::pos() const
{
    return _offset;
}

qint64 PlaceholderValidationDevice::readData(char *data, qint64 maxSize)
{
    if (_offset >= _size)
        return -1;
    if (maxSize == 0)
        return 0;
    maxSize = qMin(maxSize, static_cast<qint64>(_size - _offset));

    auto opInfo = _opdata.toOpinfo();
    opInfo.Type = CF_OPERATION_TYPE_RETRIEVE_DATA;
    opInfo.SyncStatus = nullptr; // can convey extra user-visible text through this

    CF_OPERATION_PARAMETERS opParams = {};
    opParams.ParamSize = CF_SIZE_OF_OP_PARAM(RetrieveData);
    opParams.RetrieveData.Flags = CF_OPERATION_RETRIEVE_DATA_FLAG_NONE;
    opParams.RetrieveData.Buffer = data;
    opParams.RetrieveData.Offset.QuadPart = _offset;
    opParams.RetrieveData.Length.QuadPart = maxSize;
    opParams.RetrieveData.ReturnedLength.QuadPart = 0; // will be filled with the actually read data

    HRESULT ok = CfExecute(&opInfo, &opParams);
    if (FAILED(ok)) {
        qCWarning(lcVfs) << "CfExecute error in readData" << Utility::formatWinError(ok);
        return -1;
    }

    auto readAmount = opParams.RetrieveData.ReturnedLength.QuadPart;
    _offset += readAmount;
    return readAmount;
}

bool PlaceholderValidationDevice::atEnd() const
{
    return _offset >= _size;
}

}
