#include <stdio.h> // strcpy(), strncpy()
#include <string.h> // strcpy(), strncpy()

#include "screen.h"
#include "input.h"
#include "line.h"

Input::Input( Screen* newScreen, int x0, int y0, int w0, int h0 )
  : Bitmap( newScreen, x0, y0, w0, h0 )
{
  upper = new Line( newScreen, getX(), getY(), getX()+getWidth()-1, getY() );
  left  = new Line( newScreen, getX(), getY(), getX(), getY()+getHeight()-1 );
  right = new Line( newScreen, getX()+getWidth()-1, getY(), getX()+getWidth()-1, getY()+getHeight()-1 );
  lower = new Line( newScreen, getX(), getY()+getHeight()-1, getX()+getWidth()-1, getY()+getHeight()-1 );
  maxChars = (getWidth()-4)/screen->getFontWidth();
  sBuffer = new char[ maxChars+1 ];
  bBuffer = NULL;
  cursorPos = 0;
}

Input::~Input()
{
  restoreBackground();
  if( upper )
    delete upper;
  if( lower )
    delete lower;
  if( left )
    delete left;
  if( right )
    delete right;
}

char* Input::start()
{
  int key;
  int x0 = getX()+2;
  int y0 = getY()+2;
  int i = cursorPos;

  screen->mouseOff();
  draw();

  screen->print( x0, y0, sBuffer );
  x0 += cursorPos*screen->getFontWidth();

  while( ( key = screen->getChar() ) != SKEY_ENTER )
  {
    if( key == SKEY_ESCAPE )
    {
      screen->mouseOn();
      return NULL;
    }
    if( key == SKEY_BACKSPACE ) // Backspace
    {
      if( i <= 0 )
        continue;
      x0 -= screen->getFontWidth();
      screen->print( x0, y0, ' ' );
      --i;
      key = '\0';
    }
    else
    {
      if( i >= maxChars )
        continue;
      screen->print( x0, y0, (char) key );
      sBuffer[i++] = (char) key;

      x0 += screen->getFontWidth();
    }
  }
  sBuffer[i] = '\0';

  cursorPos = i;
  screen->mouseOn();
  return sBuffer;
}

void Input::setText( char* text )
{
  if( strlen( text ) > (unsigned int ) maxChars )
  {
     strncpy( sBuffer, text, maxChars );
     sBuffer[maxChars] = '\0';
  }
  else
    strcpy( sBuffer, text );

  cursorPos = strlen( sBuffer );
}

void Input::draw()
{
  screen->mouseOff();
  saveBackground();
  screen->setArea( getX(), getY(), getWidth(), getHeight(), screen->getBgc() );
  upper->draw();
  right->draw();
  left->draw();
  lower->draw();
  screen->mouseOn();
}
