#include <X11/cursorfont.h>
#include <X11/Xatom.h>

#include "OXMyTextEntry.h"

int OXMyTextEntry::HandleKey(XKeyEvent *event) {
  int  modifier, n, len, text_changed = False;
  char tmp[10];
  KeySym keysym;
  XComposeStatus compose = { NULL, 0 };

  len = _text->GetTextLength();
  n = XLookupString(event, tmp, sizeof(tmp)-1, &keysym, &compose);
  tmp[n] = 0;

  switch (keysym) {
    case XK_Right:
      if (_selection_on) _selection_on = False;
      if (_cursor_ix < len) ++_cursor_ix;
      break;

    case XK_Left:
      if (_selection_on) _selection_on = False;
      if (_cursor_ix > 0) --_cursor_ix;
      break;

    case XK_Home:
      if (_selection_on) _selection_on = False;
      _cursor_ix = 0;
      break;

    case XK_End:
      if (_selection_on) _selection_on = False;
      _cursor_ix = len;
      break;

    case XK_Delete:
      if (_selection_on) {
        int start, ns;

        start = min(_start_ix, _end_ix);
        ns = abs(_end_ix - _start_ix);
        _text->RemoveText(start, ns);
        _selection_on = False;
        _cursor_ix = start;
      } else {
        _text->RemoveText(_cursor_ix, 1);
      }
      text_changed = True;
      break;

    case XK_BackSpace:
      if (_selection_on) {
        int start, ns;

        start = min(_start_ix, _end_ix);
        ns = abs(_end_ix - _start_ix);
        _text->RemoveText(start, ns);
        _selection_on = False;
        _cursor_ix = start;
      } else {
        if (_cursor_ix > 0) {
          --_cursor_ix;
          _text->RemoveText(_cursor_ix, 1);
        }
      }
      text_changed = True;
      break;

    case XK_Return:
      text_changed = True;
    case XK_Up:
    case XK_Down:
    case XK_Escape:
    case XK_Execute:
      break;    

    default:
      if (_selection_on) {
        int start, ns;

        start = min(_start_ix, _end_ix);
        ns = abs(_end_ix - _start_ix);
        _text->RemoveText(start, ns);
        _selection_on = False;
        _cursor_ix = start;
      }
      _text->AddText(_cursor_ix, tmp);
      len = _text->GetTextLength();
      _cursor_ix += n;
      if (_cursor_ix > len) _cursor_ix = len;
      text_changed = True;
      break;
  }
  if (text_changed)
    SendMessage(_msgWindow, MK_MSG(XC_TEXTENTRY, TE_TEXTCHANGED),
                _widgetID, keysym);
                //_widgetID, 0L);

  _cursor_x = 4 + XTextWidth(_fontStruct, _text->GetString(), _cursor_ix);
  _client->NeedRedraw(this);
  return True;
}
