/***************************************************************************
    copyright            : (C) 2005-2006 by Robby Stephenson
    email                : robby@periapsis.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of version 2 of the GNU General Public License as  *
 *   published by the Free Software Foundation;                            *
 *                                                                         *
 ***************************************************************************/

#include "overlaywidget.h"

#include <tqlayout.h>

using Tellico::GUI::OverlayWidget;

OverlayWidget::OverlayWidget(TQWidget* parent, TQWidget* anchor) : TQFrame(parent)
    , m_anchor(anchor)
    , m_corner(TopRight) {
  m_anchor->installEventFilter(this);
  reposition();
  hide();
}

void OverlayWidget::setCorner(Corner corner_) {
  if(corner_ == m_corner) {
    return;
  }
  m_corner = corner_;
  reposition();
}

void OverlayWidget::addWidget(TQWidget* widget_) {
  layout()->add(widget_);
  adjustSize();
}

void OverlayWidget::reposition() {
  if(!m_anchor) {
    return;
  }

  setMaximumSize(parentWidget()->size());
  adjustSize();

  TQPoint p;

  switch(m_corner) {
    case BottomLeft:
      p.setX(0);
      p.setY(m_anchor->height());
      break;

    case BottomRight:
      p.setX(m_anchor->width() - width());
      p.setY(m_anchor->height());
      break;

    case TopLeft:
      p.setX(0);
      p.setY(-1 * height());
      break;

    case TopRight:
      p.setX(m_anchor->width() - width());
      p.setY(-1 * height());
  }

  // Position in the toplevelwidget's coordinates
  TQPoint pTopLevel = m_anchor->mapTo(topLevelWidget(), p);
  // Position in the widget's parentWidget coordinates
  TQPoint pParent = parentWidget()->mapFrom(topLevelWidget(), pTopLevel);
  // keep it on the screen
  if(pParent.x() < 0) {
    pParent.rx() = 0;
  }
  move(pParent);
}

bool OverlayWidget::eventFilter(TQObject* object_, TQEvent* event_) {
  if(TQT_BASE_OBJECT(object_) == TQT_BASE_OBJECT(m_anchor) && (event_->type() == TQEvent::Move || event_->type() == TQEvent::Resize)) {
    reposition();
  }

  return TQFrame::eventFilter(object_, event_);
}

void OverlayWidget::resizeEvent(TQResizeEvent* event_) {
  reposition();
  TQFrame::resizeEvent(event_);
}

bool OverlayWidget::event(TQEvent* event_) {
  if(event_->type() == TQEvent::ChildInserted) {
    adjustSize();
  }

  return TQFrame::event(event_);
}

#include "overlaywidget.moc"
