// render_selection.cpp — see the header.
//
// Compiled into the reaper_reasampler module. Includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU that defines the API
// pointers; here they are extern.

#include "shell/capture/render_selection.h"

#define REAPERAPI_MINIMAL
#define REAPERAPI_WANT_CountTracks
#define REAPERAPI_WANT_GetTrack
#define REAPERAPI_WANT_CountSelectedTracks
#define REAPERAPI_WANT_GetSelectedTrack
#define REAPERAPI_WANT_SetTrackSelected
#include "reaper_plugin_functions.h"

namespace reasampler::capture {

namespace {

// Deselect every track in GetTrack's index space, then select exactly `tracks` — so
// the resulting selection is the set, not the set unioned with whatever was already
// selected. That index space holds no master track (the master is reached only via
// GetMasterTrack); the header states this nowhere, so treat it as behavior rather
// than a documented guarantee.
void selectOnly(const std::vector<MediaTrack*>& tracks)
{
    const int total = CountTracks(nullptr);
    for (int i = 0; i < total; ++i)
        if (MediaTrack* tr = GetTrack(nullptr, i))
            SetTrackSelected(tr, false);
    for (MediaTrack* tr : tracks)
        if (tr) SetTrackSelected(tr, true);
}

}  // namespace

RenderTrackSelection::RenderTrackSelection(const std::vector<MediaTrack*>& tracks)
{
    if (tracks.empty()) return;

    const int n = CountSelectedTracks(nullptr);  // nullptr = active project
    for (int i = 0; i < n; ++i)
        if (MediaTrack* tr = GetSelectedTrack(nullptr, i))
            original_.push_back(tr);

    selectOnly(tracks);
    applied_ = true;
}

RenderTrackSelection::~RenderTrackSelection()
{
    if (applied_) selectOnly(original_);
}

}  // namespace reasampler::capture
