/* gstreamermm - a C++ wrapper for gstreamer
 *
 * Copyright 2008 The gstreamermm Development Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdexcept>
#include <gst/gstbin.h>
#include <gst/gstutils.h>
#include <gstreamermm/pad.h>
#include <gstreamermm/iterator.h>

_PINCLUDE(glibmm/private/object_p.h)
_PINCLUDE(gstreamermm/private/element_p.h)

namespace Gst
{

Bin::Bin()
: _CONSTRUCT("name", NULL)
{}


Glib::RefPtr<Gst::Bin> Bin::add(const Glib::RefPtr<Gst::Element>& element)
{
  // The following is needed because when adding an element to a bin, the bin
  // likes to have the last reference and then destroy it when the bin itself
  // is destroyed.  Without the extra reference, when the last Glib::RefPtr<>
  // to the element goes out of scope, the element may be destroyed before the
  // bin and GStreamer complains about it.  The extra reference to the element
  // is removed when the bin is destroyed or when the element is removed from
  // the bin (see gst_bin_remove).
  if (G_LIKELY(GST_OBJECT_IS_FLOATING(element->gobj())))
    element->reference();

  const bool result = gst_bin_add(gobj(), element->gobj());

  // If addition successful, return RefPtr<..> to this bin, otherwise return
  // NULL RefPtr<...>
  if(result)
    return Glib::wrap(gobj(), true);
  else
    throw std::runtime_error("Failed to add " + element->get_name() + " element");
}

Glib::RefPtr<Gst::Bin> Bin::remove(const Glib::RefPtr<Gst::Element>& element)
{
  const bool result = gst_bin_remove(gobj(), element->gobj());

  // If removal successful, return RefPtr<..> to this bin, otherwise return
  // NULL RefPtr<...>
  if(result)
    return Glib::wrap(gobj(), true);
  else
    return Glib::RefPtr<Gst::Bin>(0);
}

} //namespace Gst
