#include "AddReferenceCommand.h"
#include "../../utils/Logger.h"
#include <pxr/usd/usd/references.h>
#include <pxr/base/tf/token.h>

namespace UsdLayerManager {

AddReferenceCommand::AddReferenceCommand(pxr::UsdStageRefPtr  stage,
                                         const pxr::SdfPath&  xformPath,
                                         const std::string&   refFilePath)
    : m_stage(stage)
    , m_xformPath(xformPath)
    , m_refFilePath(refFilePath)
    , m_description("Add Reference " + refFilePath)
{
}

void AddReferenceCommand::Execute() {
    if (!m_stage) return;
    try {
        pxr::UsdPrim xformPrim = m_stage->DefinePrim(m_xformPath, pxr::TfToken("Xform"));
        if (!xformPrim.IsValid()) {
            LOG_ERROR("AddReferenceCommand: failed to define Xform at " + m_xformPath.GetString());
            return;
        }
        if (!xformPrim.GetReferences().AddReference(m_refFilePath))
            LOG_ERROR("AddReferenceCommand: failed to add reference " + m_refFilePath);
    } catch (const std::exception& e) {
        LOG_ERROR(std::string("AddReferenceCommand::Execute error: ") + e.what());
    }
}

void AddReferenceCommand::Undo() {
    if (!m_stage) return;
    try {
        if (!m_stage->RemovePrim(m_xformPath))
            LOG_ERROR("AddReferenceCommand::Undo: failed to remove prim " + m_xformPath.GetString());
    } catch (const std::exception& e) {
        LOG_ERROR(std::string("AddReferenceCommand::Undo error: ") + e.what());
    }
}

} // namespace UsdLayerManager
