#include "_ninput.h"

using namespace yatl;
using namespace fl;

#include <string.h>
#include <stdlib.h>

#include <FL/Fl.h>
#include <FL/fl_ask.H>

_ninput::_ninput(int x,int y,int w,int h,char *l): Fl_Input(x,y,w,h,l)
{
  type(FL_FLOAT_INPUT);
  if(type()==FL_FLOAT_INPUT || type()==FL_INT_INPUT)
  {
    value("0");
    position(0,1);
  }
}

int _ninput::handle(int event)
{
  static int dnd_save_position, dnd_save_mark, drag_start = -1, newpos;
  static Fl_Widget *dnd_save_focus;

  switch (event)
  {
    case FL_KEYBOARD:
      if(Fl::event_key() == FL_Tab && mark() != position())
      {
        // Set the current cursor position to the end of the selection...
        if(mark() > position()) position(mark());
        else position(position());
        return (1);
      }
      else
      {
        return handle_key();
      }
    default:
      return Fl_Input::handle(event);
  }
}

int _ninput::handle_key()
{
  char ascii = Fl::event_text()[0];
  int repeat_num=1;
  int del;

  const char zero = '0';

  if(Fl::compose(del))
  { // Insert characters into numeric fields after checking for legality:
    if (readonly())
    {
      fl_beep();
      return 1;
    }

    if(input_type() == FL_INT_INPUT)
    {
      Fl::compose_reset(); // ignore any foreign letters...

      int pos = position()>mark() ? mark() : position();
      int mar = position()<mark() ? mark() : position();

      if(ascii >= '0' && ascii <= '9')
      {
        if(!pos && (index(0)=='-' || index(0)=='+'))
        { // don't insert number before the sign
          if(mar>0) replace(0,mar,&ascii,1);
        }
        else replace(position(),mark(),&ascii,1);
      }
      else if((ascii == '+' || ascii == '-'))
      {
        if(!pos)
        {
          if(mar==0) // mark == porition
          { // don't insert a sign before another sign
            if(index(0)!='-' && index(0)!='+') replace(0,0,&ascii,1);
          }
          else replace(0,mar,&ascii,1);

          if(!index(1)) // if value()=="-" -> make it "-0"
          {
            replace(1,1,&zero,1);
            position(1,2);
          }
        }
      }
      return 1;
    }
    else if(input_type() == FL_FLOAT_INPUT)
    {
      Fl::compose_reset(); // ignore any foreign letters...

      int pos = position()>mark() ? mark() : position();
      int mar = position()<mark() ? mark() : position();

      if(ascii >= '0' && ascii <= '9')
      {
        if(index(mar)=='-' || index(mar)=='+')
        { // don't insert number before a sign
        }
        else replace(pos,mar,&ascii,1);
      }
      else if((ascii == '+' || ascii == '-'))
      {
        if(!pos)
        {
          if(mar==0) // mark == porition
          { // don't insert a sign before another sign
            if(index(0)!='-' && index(0)!='+') replace(0,0,&ascii,1);
          }
          else replace(0,mar,&ascii,1);

          if(!index(1)) // if value()=="-" -> make it "-0"
          {
            replace(1,1,&zero,1);
            position(1,2);
          }
        }
        else if(tolower(index(pos-1))=='e' && index(mar)!='-' && index(mar)!='+')
        { // insert sign if only if we don't insert before another sign
          replace(pos,mar,&ascii,1);
          if(!index(mar))
          { // but check there is still something afther
            replace(position(),position(),&zero,1);
            position(position()-1,position());
          }
        }
      }
      else if(ascii=='.')
      {
        long e = strcspn(value(),"eE");
        long s = strcspn(value(),"+-");
        long p = strcspn(value(),".");

        if(s==strlen(value()) || s>e) s = -1;
        if(e==strlen(value())) e++;
        if(p==strlen(value())) p = 0;

        if(index(mar)=='-' || index(mar)=='+' || pos>=e || pos<=s+1)
        { // never add before the sign or afther the e
        }
        else
        {
          if(!p || (p>pos && p<mar))
          {
            replace(pos,mar,&ascii,1);

            if(!index(position()))
            {
              replace(position(),position(),&zero,1);
              position(position()-1,position());
            }
          }
        }
      }
      else if(tolower(ascii)=='e')
      {
        long e = strcspn(value(),"eE");
        long s = strcspn(value(),"+-");
        long p = strcspn(value(),".");

        if(e==strlen(value())) e = 0;
        if(p==strlen(value())) p = -1;
        if(p<0 && s<1) p = 0;

        if(pos>p+1)
        {
          if(!e || (e>pos && e<mar))
          {
            replace(pos,mar,&ascii,1);

            if(!index(position()))
            {
              replace(position(),position(),&zero,1);
              position(position()-1,position());
            }
          }
        }
      }
      return 1;
    }
    else if (del || Fl::event_length())
    {
      replace(position(), del ? position()-del : mark(),Fl::event_text(), Fl::event_length());
    }
    return 1;
  }

  switch (Fl::event_key())
  {
    case FL_Insert:
      if (Fl::event_state() & FL_CTRL) ascii = ctrl('C');
      else if (Fl::event_state() & FL_SHIFT) ascii = ctrl('V');
      break;
    case FL_Delete:
      if (Fl::event_state() & FL_SHIFT) ascii = ctrl('X');
      else ascii = ctrl('D');
      break;
    case FL_Left:
      ascii = ctrl('B'); break;
    case FL_Right:
      ascii = ctrl('F'); break;
    case FL_Page_Up:
      repeat_num=5; //temporary hack
                    //TODO: find number of lines in window and use it instead 5
    case FL_Up:
      ascii = ctrl('P'); break;
    case FL_Page_Down:
      repeat_num=5; //temporary hack
                    //TODO: find number of lines in window and use it instead 5
    case FL_Down:
      ascii = ctrl('N'); break;
    case FL_Home:
      if (Fl::event_state() & FL_CTRL)
      {
        shift_position(0);
        return 1;
      }
      ascii = ctrl('A');
      break;
    case FL_End:
      if (Fl::event_state() & FL_CTRL)
      {
        shift_position(size());
        return 1;
      }
      ascii = ctrl('E');
      break;
    case FL_BackSpace:
      ascii = ctrl('H'); break;
    case FL_Enter:
    case FL_KP_Enter:
      if (when() & FL_WHEN_ENTER_KEY)
      {
        position(size(), 0);
        maybe_do_callback();
        return 1;
      }
      else if (input_type() == FL_MULTILINE_INPUT && !readonly())
        return replace(position(), mark(), "\n", 1);
      else
        return 0;	// reserved for shortcuts
    case FL_Tab:
      if (Fl::event_state(FL_CTRL|FL_SHIFT) || input_type()!=FL_MULTILINE_INPUT || readonly()) return 0;

      return replace(position(), mark(), &ascii, 1);
      #ifdef __APPLE__
        case 'c' :
        case 'v' :
        case 'x' :
        case 'z' :
      //    printf("'%c' (0x%02x) pressed with%s%s%s%s\n", ascii, ascii,
      //           Fl::event_state(FL_SHIFT) ? " FL_SHIFT" : "",
      //           Fl::event_state(FL_CTRL) ? " FL_CTRL" : "",
      //           Fl::event_state(FL_ALT) ? " FL_ALT" : "",
      //           Fl::event_state(FL_META) ? " FL_META" : "");
          if (Fl::event_state(FL_META)) ascii -= 0x60;
      //    printf("using '%c' (0x%02x)...\n", ascii, ascii);
          break;
      #endif // __APPLE__
  }

  int i;
  switch (ascii)
  {
    case ctrl('A'):
      return shift_position(line_start(position())) + NORMAL_INPUT_MOVE;
    case ctrl('B'):
      return shift_position(position()-1) + NORMAL_INPUT_MOVE;
    case ctrl('C'): // copy
      return copy(1);
    case ctrl('D'):
    case ctrl('?'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }

      if(mark()!=position()) cut();
      else cut(1);

      if(input_type()==FL_INT_INPUT)
      {
        if(!index(0))
        {
          replace(0,0,&zero,1);
          position(0,1);
        }
        else if((index(0)=='-' || index(0)=='+') && !index(1))
        {
          replace(1,1,&zero,1);
          position(1,2);
        }
      }
      else if(input_type()==FL_FLOAT_INPUT)
      {
        if(!index(0))
        {
          replace(0,0,&zero,1);
          position(0,1);
        }
        else if((index(position()-1)=='-' ||
                 index(position()-1)=='+' ||
                 index(position()-1)=='.' ||
                 index(position()-1)=='e' ||
                 index(position()-1)=='E') && !index(position()))
        {
          replace(position(),position(),&zero,1);
          position(position()-1,position());
        }
      }
      break;
    case ctrl('H'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }

      if(mark()!=position()) cut();
      else cut(-1);

      if(input_type()==FL_INT_INPUT)
      {
        if(!index(0))
        {
          replace(0,0,&zero,1);
          position(0,1);
        }
        else if((index(0)=='-' || index(0)=='+') && !index(1))
        {
          replace(1,1,&zero,1);
          position(1,2);
        }
      }
      else if(input_type()==FL_FLOAT_INPUT)
      {
        if(!index(0))
        {
          replace(0,0,&zero,1);
          position(0,1);
        }
        else if((index(position()-1)=='-' ||
                 index(position()-1)=='+' ||
                 index(position()-1)=='.' ||
                 index(position()-1)=='e' ||
                 index(position()-1)=='E') && !index(position()))
        {
          replace(position(),position(),&zero,1);
          position(position()-1,position());
        }
      }
      break;
    case ctrl('K'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }
      if(position()>=size()) return 0;
      i = line_end(position());
      if (i == position() && i < size()) i++;

      cut(position(), i);

      if(input_type()==FL_INT_INPUT)
      {
        if(!index(0))
        {
          replace(0,0,&zero,1);
          position(0,1);
        }
        else if((index(0)=='-' || index(0)=='+') && !index(1))
        {
          replace(1,1,&zero,1);
          position(1,2);
        }
      }
      else if(input_type()==FL_FLOAT_INPUT)
      {
        if(!index(0))
        {
          replace(0,0,&zero,1);
          position(0,1);
        }
        else if((index(position()-1)=='-' ||
                 index(position()-1)=='+' ||
                 index(position()-1)=='.' ||
                 index(position()-1)=='e' ||
                 index(position()-1)=='E') && !index(position()))
        {
          replace(position(),position(),&zero,1);
          position(position()-1,position());
        }
      }
      return copy_cuts();
    case ctrl('U'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }
      return cut(0, size());
    case ctrl('E'):
      return shift_position(line_end(position())) + NORMAL_INPUT_MOVE;
    case ctrl('F'):
      return shift_position(position()+1) + NORMAL_INPUT_MOVE;
    case ctrl('N'):
      i = position();
      while (repeat_num--)
      {
        i = line_end(i);
        if (i >= size()) return NORMAL_INPUT_MOVE;
        i++;
      }
      shift_up_down_position(i);
      return 1;
    case ctrl('P'):
      i = position();
      while(repeat_num--)
      {
        i = line_start(i);
        if (!i) return NORMAL_INPUT_MOVE;
        i--;
      }
      shift_up_down_position(line_start(i));
      return 1;
    case ctrl('V'):
    case ctrl('Y'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }
      Fl::paste(*this,1);
      return 1;
    case ctrl('X'):
    case ctrl('W'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }
      copy(1);
      return cut();
    case ctrl('Z'):
    case ctrl('_'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }
      return undo();
    case ctrl('I'):
    case ctrl('J'):
    case ctrl('L'):
    case ctrl('M'):
      if (readonly())
      {
        fl_beep();
        return 1;
      }
      // insert a few selected control characters literally:
      if (input_type() != FL_FLOAT_INPUT && input_type() != FL_INT_INPUT)
        return replace(position(), mark(), &ascii, 1);
  }
  return 0;
}

int _ninput::shift_position(int p)
{
  return position(p, Fl::event_state(FL_SHIFT) ? mark() : p);
}

int _ninput::shift_up_down_position(int p)
{
  return up_down_position(p, Fl::event_state(FL_SHIFT));
}
