/*
 *  mdc_magnet.cpp
 *  mdcanvas
 *
 *  Created by Alfredo Kojima on 07/May/2.
 *  Copyright 2007 MySQL AB. All rights reserved.
 *
 */

#include "stdafx.h"


#include "mdc_magnet.h"
#include "mdc_canvas_item.h"
#include "mdc_connector.h"

using namespace mdc;


Magnet::Magnet(CanvasItem *owner)
: _owner(owner)
{
  _owner->signal_bounds_changed().connect(sigc::mem_fun(this, &Magnet::owner_bounds_changed));
  _owner->signal_parent_bounds_changed().connect(sigc::mem_fun(this, &Magnet::owner_parent_bounds_changed));
}


Magnet::~Magnet()
{
  remove_all_connectors();
}


void Magnet::remove_all_connectors()
{
  std::list<Connector*>::iterator iter;
  while ((iter= _connectors.begin()) != _connectors.end())
  {
    (*iter)->disconnect();
  }
}


bool Magnet::add_connector(Connector *conn)
{
  _connectors.push_back(conn);

  return true;
}


void Magnet::remove_connector(Connector *conn)
{
  _connectors.remove(conn);
}


void Magnet::notify_connected()
{
  std::list<Connector*> list(_connectors);

  for (std::list<Connector*>::iterator iter= list.begin();
    iter != list.end(); ++iter)
    (*iter)->magnet_moved(this);
}


void Magnet::set_connection_validator(const sigc::slot<bool, Connector*> &slot)
{
  _connection_slot= slot;
}


void Magnet::set_disconnection_validator(const sigc::slot<bool, Connector*> &slot)
{
  _disconnection_slot= slot;
}


bool Magnet::allows_connection(Connector *conn) const
{
  if (_connection_slot)
    return _connection_slot(conn);
  return true;
}


bool Magnet::allows_disconnection(Connector *conn) const
{
  if (_disconnection_slot)
    return _disconnection_slot(conn);

  return true;
}


Point Magnet::get_position_for_connector(Connector *conn, const Point &srcpos) const
{
  return _owner->get_intersection_with_line_to(srcpos);
}


Point Magnet::get_position() const
{
  return _owner->get_root_bounds().center();
}


void Magnet::owner_parent_bounds_changed(CanvasItem *item, const Rect &obounds)
{
  if (item->get_bounds() != obounds)
    notify_connected();
}


void Magnet::owner_bounds_changed(const Rect &obounds)
{
  // notify listening connections that we have been moved
  if (obounds != _owner->get_bounds())
    notify_connected();
}


