//----------------------------------------------------------------------------
///
///   \brief
///
//----------------------------------------------------------------------------

#include <fosh/ansi.h>
#include <lepto/log.h>
#include <lepto/base64.h>
//#include <lepto/telegram.h>

CAnsi::CAnsi()
{
   current=0;
   eAnsiState=eAnsiStateNone;

   return;
}

#define CByteArray QByteArray
#define CString QString

int CAnsi::digest(signed char c)
{
   switch(eAnsiState)
   {
      // Fresh as new born
      case(eAnsiStateNone):
         current=0;
         switch(c)
         {
            case 27:
               current|=c;
               eAnsiState=eAnsiStateEscaped;
               break;
            default:
               return(c);
               break;
         }
         break;


      // ESC was send
      case(eAnsiStateEscaped):
         switch(c)
         {
            case '[':
               current=(current<<8)|c;
               eAnsiState=eAnsiStateCsi;
               break;
            case '#':
               eAnsiState=eAnsiStateTelegram;
               break;
            default:
               eAnsiState=eAnsiStateNone;
               return(-1);
               break;
         }
         break;

      // ESC[ was send
      case(eAnsiStateCsi):
         switch(c)
         {
            case '0' ... '9':
               current=(current<<8)|c;
               break;
            default:
               current=(current<<8)|c;
               eAnsiState=eAnsiStateNone;
               return(current);
               break;
         }
         break;

      case(eAnsiStateTelegram):
         if(c==';')
         {
            eAnsiState=eAnsiStateNone;
            lInfo( "Telegram arived!" );
            CByteArray serialized;
            // TBD
            //CBase64::decode(telegram, serialized);

            // TBD
            //newTelegram.emitSignal(serialized);
            telegram.clear();
            return(0);
         }
         else
            telegram+=(char)c;
         break;
      // Whooot?
      default:
          eAnsiState=eAnsiStateNone;
         return( -1 );
         break;
   }

   return(0);
}


bool isAscii(int i)
{
   return(  ( i > 0 ) && ( i != 0x1b ) && ( i < 0x80 ) );
};


//---fin----------------------------------------------------------------------
