#include <string.h> // strchr();
#include "line.h"
#include "menu.h"
#include "notice.h"

Menu::Menu( Screen* newScreen, int x0, int y0 )
  : Bitmap( newScreen, x0, y0, 0, 4 )
{
  //width  = 0;
  //height = 4;
  //bBuffer = NULL;
}

Menu::~Menu()
{
  restoreBackground();
  list.emptyWithElementDelete();
  if( upper )
    delete upper;
  if( lower )
    delete lower;
  if( left )
    delete left;
  if( right )
    delete right;
}

int Menu::start()
{
  int key;
  screen->mouseOff();

  draw();

  while( 1 )
  {
    key = screen->getKey();
    if( key == SKEY_ESCAPE )
      break;

    if( _isKeyOk(key) )
    {
      screen->mouseOn();
      return key;
    }
  }
  screen->mouseOn();
  return 0;
}

void Menu::addEntry( char* text )
{
  char* s = new char[strlen( text+1 ) ];
  int w = (strlen( text ) -1) * screen->getFontWidth() + 4;
  strcpy( s, text );
  list.append( s );
  if( getWidth() < w )
    setWidth( w );
  setHeight( getHeight() + screen->getFontHeight() );
}

void Menu::draw()
{
  screen->mouseOff();
  int cy = getY() + 2;
  upper = new Line( screen, getX(), getY(), getX()+getWidth()-1, getY() );
  left  = new Line( screen, getX(), getY(), getX(), getY()+getHeight()-1 );
  right = new Line( screen, getX()+getWidth()-1, getY(), getX()+getWidth()-1, getY()+getHeight()-1 );
  lower = new Line( screen, getX(), getY()+getHeight()-1, getX()+getWidth()-1, getY()+getHeight()-1 );
  saveBackground();
  screen->setArea( getX(), getY(), getWidth(), getHeight(), screen->getBgc() );
  upper->draw();
  right->draw();
  left->draw();
  lower->draw();

  for( list.first(); !list.isLast(); list.next() )
  {
    int cx = getX() + 2;
    char* s=list.retrieve();
    for( int i = 0; i < (int) strlen( s ); i++ )
    {
      if( s[i] == '~' )
      {
        i++;
        screen->setFgc( screen->Red() );
        screen->print( cx, cy, s[i] );
        screen->setFgc( screen->White() );
      }
      else
      {
        screen->print( cx, cy, s[i] );
      }
      cx += screen->getFontWidth();
    }
    cy += screen->getFontHeight();
  }
  screen->mouseOn();
}

Bool Menu::_isKeyOk( int key )
{
  for( list.first(); !list.isLast(); list.next() )
  {
    char* s = list.retrieve();
    if( (s=strchr( s, '~' )) != NULL )
    {
      if( *(s+1)==key )
        return 1;
    }
  }
  return 0;
}
