//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      PyCore/Embed/PyObjectPtr.cpp
//! @brief     Implements class PyObjectPtr.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "PyObjectPtr.h"
#include "PyInterpreter.h"

PyObjectPtr::PyObjectPtr(PyObject* pyobject_ptr, const bool borrowed)
    : m_ptr{pyobject_ptr}
    , m_borrowed{borrowed}
{
}

PyObjectPtr::~PyObjectPtr()
{
    discard();
}

PyObjectPtr::PyObjectPtr(PyObjectPtr&& other)
    : PyObjectPtr(other.release())
{
}
PyObject* PyObjectPtr::release()
{
    PyObject* pyobject_ptr{m_ptr};
    reset();
    return pyobject_ptr;
}

void PyObjectPtr::reset()
{
    m_ptr = nullptr;
}

void PyObjectPtr::discard()
{
    if (m_borrowed) {
        // borrowed reference need no reference decrement
        reset();
        return;
    }

    PyInterpreter::DecRef(m_ptr);
    reset();
}

bool PyObjectPtr::valid() const
{
    return static_cast<bool>(m_ptr);
}
