// (c) 2000 Peter Putzer

#include <tqlineedit.h>

#include <kdebug.h>

#include "ksv_core.h"
#include "SpinBox.h"

KSVSpinBox::KSVSpinBox (TQWidget* parent, const char* name)
  : TQSpinBox (0, 99, 1, parent, name),
    TDECompletionBase (),
    mClearedSelection (false)
{
  TDECompletion* comp = ksv::numberCompletion();
  setCompletionObject (comp, true);

  editor()->installEventFilter (this);

  connect (editor(), TQ_SIGNAL (textChanged (const TQString&)),
           comp, TQ_SLOT (slotMakeCompletion (const TQString&)));
  connect (comp, TQ_SIGNAL (match (const TQString&)),
           this, TQ_SLOT (handleMatch (const TQString&)));
}

KSVSpinBox::~KSVSpinBox ()
{
}

TQString KSVSpinBox::mapValueToText (int value)
{
  TQString result;

  if (value < 10)
    result.sprintf("%.2i", value);
  else
    result.setNum (value);
  
  return result;
}

void KSVSpinBox::setCompletedText (const TQString& text)
{
  TQLineEdit* e = editor ();
  const int pos = e->cursorPosition();

  e->setText (text);

  e->setSelection (pos, text.length());
  e->setCursorPosition (pos);
}

void KSVSpinBox::setCompletedItems (const TQStringList& /*items*/)
{
  // dont know what is supposed to be in here but it has to be defined
  // because else the lack of this damn thing is making it abstract
}

void KSVSpinBox::handleMatch (const TQString& match)
{
  if (!match.isNull() && editor()->text().length() < 2 && !mClearedSelection)
    setCompletedText (match);
}

bool KSVSpinBox::eventFilter (TQObject* o, TQEvent* e)
{
  Q_UNUSED(o);
  if (e->type() == TQEvent::KeyPress)
    {
      TQKeyEvent* ke = static_cast<TQKeyEvent*>(e);
      
      switch (ke->key())
        {
        case Key_BackSpace:
        case Key_Delete:
          mClearedSelection = true;
          break;

        default:
          mClearedSelection = false;
        }
    }

  return false;
}

#include "SpinBox.moc"
