#include "stdafx.h"

//#include <assert.h>

#include <grts/structs.ui.h>

#include <grtpp_util.h>
#include "mforms_ObjectReference_impl.h"

#include <typeinfo>

#include "mforms/base.h"

//================================================================================
// mforms_ObjectReference


grt::IntegerRef mforms_ObjectReference::valid() const
{
  if (_data)
    return grt::IntegerRef(1);
   else
    return grt::IntegerRef(0);
}

grt::IntegerRef mforms_ObjectReference::isEqualTo(const grt::Ref<mforms_ObjectReference> &other)
{
  if (_data == NULL && other->get_data() == NULL)
    return grt::IntegerRef(1);
  
  if (_data && other->get_data())
    return grt::IntegerRef(_data == other->get_data() ? 1 : 0);
  return grt::IntegerRef(1);
}


mforms::Object *mforms_from_grt(mforms_ObjectReferenceRef object)
{
  if (!object.is_valid() || !*object->valid())
     return 0;
  return object->get_data();
}


static void release_object(mforms::Object *object)
{
  if (object)
    object->release();
}

mforms_ObjectReferenceRef mforms_to_grt(grt::GRT *grt, mforms::Object *object, const std::string &type_name)
{
  if (object)
  {
    // view is not necessarily managed, in some cases the view must be deleted by the caller
    //assert(object->is_managed());

    mforms_ObjectReferenceRef ref(grt);
    object->retain();
    ref->set_data(object, release_object);
    ref->type(grt::StringRef(type_name.empty() ? grt::get_type_name(typeid(*object)) : type_name));
    return ref;
  }
  return mforms_ObjectReferenceRef();
}

