#include "aguix.h"
#include "widget.h"
#include "awindow.h"

Widget::Widget( AGUIX *aguix ) : Focus(),
				 _parent( NULL ),
				 _created( false ),
				 _aguix( aguix ),
				 _x( 0 ),
				 _y( 0 ),
				 _w( 0 ),
				 _h( 0 ),
				 _is_top_level_widget( false ),
                                 m_allow_timerevent_break( false ),
                                 m_nr_of_last_event_break( 0 )
{
}

Widget::~Widget()
{
  destroy();
  if ( _parent != NULL ) _parent->remove( this );
}

int Widget::create()
{
  if ( _created == true ) return 1;
  
  if ( ( _is_top_level_widget == true ) ||
       ( ( _parent != NULL ) && ( _parent->isCreated() == true ) ) ) {
    doCreateStuff();
  }
  return 0;
}

void Widget::destroy()
{
  if ( _created == false ) return;
  _aguix->widgetDestroyed( this );
  doDestroyStuff();
}

void Widget::doCreateStuff()
{
  _created = true;
}

void Widget::doDestroyStuff()
{
  _created = false;
}

int Widget::setParent( AWindow *parent )
{
  if ( ( parent != NULL ) && ( _parent == NULL ) ) {
    _parent = parent;
  } else if ( ( parent == NULL ) && ( _parent != NULL ) ) {
    _parent = NULL;
  } else {
    return 1;
  }
  return 0;
}

bool Widget::isCreated() const
{
  if ( ( _parent == NULL ) && ( _is_top_level_widget == false ) ) return false;
  return _created;
}

int Widget::handleMessageLock( XEvent *E, Message *msg )
{
  int res = 0;

  if ( ( E == NULL ) || ( msg == NULL ) ) return -1;

  // give msg to real handler if
  // 1.is the lock element
  // 2.the lock element is null
  // 3.or it's an expose msg (but then only the first time)
  if ( ( msg->lockElement == this ) ||
       ( msg->lockElement == NULL ) ||
       ( ( msg->type == Expose ) && ( msg->loop == 0 ) ) ) {
    res = ( handleMessage( E, msg ) == true ) ? 1 : 0;
  }
  return res;
}

bool Widget::contains( Widget *elem ) const
{
  return false;
}

void Widget::setIsTopLevelWidget( bool nv )
{
  _is_top_level_widget = nv;
}

int Widget::getX() const
{
  return _x;
}

int Widget::getY() const
{
  return _y;
}

int Widget::getWidth() const
{
  return _w;
}

int Widget::getHeight() const
{
  return _h;
}

bool Widget::getAllowTimerEventBreak() const
{
    return m_allow_timerevent_break;
}

void Widget::setAllowTimerEventBreak( bool nv )
{
    m_allow_timerevent_break = nv;
}

long Widget::getNrOfLastEventBreak() const
{
    return m_nr_of_last_event_break;
}

void Widget::setNrOfLastEventBreak( long t )
{
    m_nr_of_last_event_break = t;
}
