// See view_tree.h.

#include "core/view/view_tree.h"

namespace reasampler::view {

FolderTree buildFolderTree(const std::vector<TrackFolderEntry>& entries) {
    FolderTree tree;
    tree.nodes.reserve(entries.size());

    // Stack of open folder-parent GUIDs; top is the next track's parent. A
    // folder-parent's push and a closer's pop both trail their own assignment.
    std::vector<std::string> open;

    for (const TrackFolderEntry& e : entries) {
        FolderNode node;
        node.guid       = e.guid;
        node.parentGuid = open.empty() ? std::string{} : open.back();
        node.isParent   = e.folderDepth == 1;
        tree.nodes.push_back(node);

        if (e.folderDepth == 1) {
            open.push_back(e.guid);
        } else if (e.folderDepth < 0) {
            int levels = -e.folderDepth;
            while (levels-- > 0 && !open.empty()) {
                open.pop_back();
            }
        }
    }

    return tree;
}

} // namespace reasampler::view
