//
//  omnisobject.hpp
//  complib
//
//  Created by Andrei Augustin on 26/09/2023.
//  Copyright © 2023 Omnis Software Ltd. All rights reserved.
//

#ifndef omnisobject_hpp
#define omnisobject_hpp

class OmnisObject
{
public:
  OmnisObject(qobjinst pObjInst) { mRefCount=0; mObjPtr=pObjInst; }
  virtual ~OmnisObject() {}
  
  void addRef() { mRefCount++; }
  void releaseRef() { mRefCount--; if (!mRefCount) delete this; }
  
protected:
  qlong mRefCount;
  qobjinst mObjPtr;
  
};
typedef OmnisObject *OmnisObjectPtr;

class OmnisObjectContainer
{
public:
  OmnisObjectPtr mObject;
  qobjinst       mObjPtr;
  
public:
  OmnisObjectContainer(qobjinst pObjPtr, OmnisObjectPtr pNewObject) {
    mObjPtr = pObjPtr;
    mObject = pNewObject;
    if (mObject) mObject->addRef();
  }
  
  OmnisObjectContainer(qobjinst pObjPtr, OmnisObjectContainer* pObjectContainer) {
    mObjPtr = pObjPtr;
    mObject = pObjectContainer->mObject;
    if (mObject) mObject->addRef();
  }
  
  void setObject(qobjinst pObjPtr, OmnisObjectContainer* pSrc) {
    if (pSrc->mObject) pSrc->mObject->addRef();
    if (mObject) { mObject->releaseRef(); mObject = NULL;}
    mObjPtr = pObjPtr; mObject = pSrc->mObject;
  }
  
  ~OmnisObjectContainer() {
    if (mObject) { mObject->releaseRef(); mObject = 0; }
  }
  
};

#endif /* omnisobject_hpp */
