#include <maps/wikimap/mapspro/services/mrc/eye/lib/common/include/secure_config.h>
#include <maps/wikimap/mapspro/services/mrc/eye/lib/detect_panel/tests/fixture.h>

#include <maps/wikimap/mapspro/services/mrc/eye/lib/unit_test/include/frame.h>

#include <maps/wikimap/mapspro/services/mrc/libs/db/include/eye/frame_gateway.h>
#include <maps/wikimap/mapspro/services/mrc/libs/db/include/eye/recognition_gateway.h>

namespace maps::mrc::eye::tests {

Fixture::Fixture()
{
    // The config content doesn't matter in the tests for now so anyone will fit.
    static std::once_flag onceFlag;
    std::call_once(onceFlag, SecureConfig::initialize, config());

    { // create devices
        auto txn = newTxn();

        devices = {
            {db::eye::MrcDeviceAttrs{"M1"}},
        };

        db::eye::DeviceGateway(*txn).upsertx(devices);
        txn->commit();
    }

    // create frames

    const db::TId deviceId = devices[0].id();

    frames = {
        {deviceId, identical, makeUrlContext(1, "cw0"), {1920, 1080}, time()},
        {deviceId, identical, makeUrlContext(2, "cw0"), {1920, 1080}, time()},
        {deviceId, identical, makeUrlContext(3, "cw0"), {1920, 1080}, time()},

        {deviceId, onLeftSide, makeUrlContext(3, "cw90"), {1080, 1920}, time()},
        {deviceId, onLeftSide, makeUrlContext(5, "cw90"), {1080, 1920}, time()},
    };

    frames[0].setDeleted(true);

    auto insert = [&](size_t begin, size_t end)
    {
        auto txn = newTxn();

        TArrayRef ref(frames.data() + begin, frames.data() + end);
        db::eye::FrameGateway(*txn).insertx(ref);

        txn->commit();
    };

    insert(0, 1);
    insert(1, 3);
    insert(3, 5);
}

Fixture::~Fixture() {
    playground().postgres().truncateTables();
}

db::TId Fixture::frameIdAt(size_t index) const { return frames.at(index).id(); }

db::TIds Fixture::frameIdsAt(std::initializer_list<size_t> indexes) const
{
    db::TIds ids;

    for (const auto index: indexes) {
        ids.push_back(frameIdAt(index));
    }

    return ids;
}

} // namespace maps::mrc::eye::tests
