/*
    SPDX-FileCopyrightText: 2008 Friedrich W. H. Kossebau <kossebau@kde.org>

    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/

#include "abstractpiecetablechangeiftest.hpp"

// test object
#include <piecetable/abstractpiecetablechange.hpp>
// lib
#include "testpiecetablechange.hpp"
#include <piecetable/piecetable.hpp>
// Qt
#include <QTest>
// Std
#include <utility>

namespace KPieceTable {

static constexpr Size BaseSize = 100;
static constexpr Address ChangeStorageOffset = 23;

AbstractPieceTableChangeIfTest::~AbstractPieceTableChangeIfTest() = default;

//---------------------------------------------------------------- Tests -----

void AbstractPieceTableChangeIfTest::init()
{
    mPieceTableChange = createPieceTableChange();
}

void AbstractPieceTableChangeIfTest::cleanup()
{
    deletePieceTableChange(std::move(mPieceTableChange));
}

//---------------------------------------------------------------- Tests -----

void AbstractPieceTableChangeIfTest::testMerge()
{
    TestPieceTableChange testChange;

    int typeId = mPieceTableChange->type();
    QString description = mPieceTableChange->description();
    bool result = mPieceTableChange->merge(&testChange);

    QVERIFY(!result);
    QCOMPARE(mPieceTableChange->type(), typeId);
    QCOMPARE(mPieceTableChange->description(), description);
}

void AbstractPieceTableChangeIfTest::testRevertApply()
{
    PieceTable pieceTable;
    pieceTable.init(0);
    pieceTable.insert(0, BaseSize, ChangeStorageOffset);

    // do change which creates this
    changePieceTable(&pieceTable);
    std::ignore = mPieceTableChange->revert(&pieceTable);

    QCOMPARE(pieceTable.size(), BaseSize);
    for (int i = 0; i < BaseSize; ++i) {
        Piece::StorageType storageId;
        Address storageOffset;
        bool result = pieceTable.getStorageData(&storageId, &storageOffset, i);

        QVERIFY(result);
        QCOMPARE(storageOffset, i + ChangeStorageOffset);
        QCOMPARE(storageId, Piece::ChangeStorage);
    }

    // now replay changes
    std::ignore = mPieceTableChange->apply(&pieceTable);
    std::ignore = mPieceTableChange->revert(&pieceTable);

    QCOMPARE(pieceTable.size(), BaseSize);
    for (Address i = 0; i < BaseSize; ++i) {
        Piece::StorageType storageId;
        Address storageOffset;
        bool result = pieceTable.getStorageData(&storageId, &storageOffset, i);

        QVERIFY(result);
        QCOMPARE(storageOffset, i + ChangeStorageOffset);
        QCOMPARE(storageId, Piece::ChangeStorage);
    }
}

}

#include "moc_abstractpiecetablechangeiftest.cpp"
