#include "aguix.h"
#include "focus.h"

std::map<const class AWindow*, Focus*> Focus::_focus_map;

Focus::Focus() : _accept_focus( false ),
		 _can_handle_focus( false ),
		 _has_focus( false )
{
}

Focus::~Focus()
{
  std::map<const AWindow *,Focus*>::iterator it1;
  for ( it1 = _focus_map.begin(); it1 != _focus_map.end(); it1++ ) {
    if ( (*it1).second == this ) {
      _focus_map.erase( it1 );
      break;
    }
  }
}

bool Focus::getAcceptFocus() const
{
  return _accept_focus;
}

void Focus::setAcceptFocus( bool nv )
{
  if ( _can_handle_focus == false ) return;
  _accept_focus = nv;
  /*TODO release the focus if we have it?
    if ( ( nv == false ) && ( hasFocus() == true ) ) {
    //iterate through _focus_map, find this and call setFocusElement
    }*/
}

void Focus::setFocusElement( const AWindow *w, Focus *f )
{
  Focus *oldf;

  if ( w == NULL ) return;
  if ( ( f != NULL ) && ( f->getAcceptFocus() == false ) ) return;

  oldf = getFocusElement( w );

  _focus_map[w] = f;

  if ( oldf != NULL ) oldf->checkFocusState( w );
  if ( f != NULL ) f->checkFocusState( w );
}

Focus *Focus::getFocusElement( const AWindow *w )
{
  if ( w == NULL ) return NULL;
  if ( _focus_map.count( w ) != 1 ) return NULL;
  return _focus_map[w];
}

void Focus::setCanHandleFocus()
{
  _can_handle_focus = true;
}

bool Focus::getHasFocus() const
{
  return _has_focus;
}

void Focus::checkFocusState( const AWindow *w )
{
  Focus *f;
  bool old_focus = _has_focus;

  if ( w == NULL ) return;
  f = getFocusElement( w );
  if ( f != this ) _has_focus = false;
  else _has_focus = true;

  if ( _has_focus != old_focus ) {
    if ( _has_focus == true )
      gotFocus();
    else
      lostFocus();
  }
}

void Focus::lostFocus()
{
}

void Focus::gotFocus()
{
}
