// 
// File name: Pattern.cpp
//
// Discription: Описание методов класса Выборка
//
// Programmer: Vladimir P. Stasevich (SV)
//
// History: 
//    Created 24.02.2000 (SV)
//

#include "Pattern.h"
#include "Sensor.h"

TLearnPattern pattern;

void TLearnPattern::CreateNewPattern( void )
{
   DestroyPattern();
}

void TLearnPattern::DestroyPattern( void )
{
   /*elems.*/clear();
   *name = '\0';
}

TLearnPattern::LoadPattern
(
   const char *fileName
)
{
   FILE     *fp;
   unsigned  numbElems;

   CreateNewPattern();
   
   fp = fopen( fileName, "rt" );
      
   if( fp == NULL ) 
      return 1;
      
   fscanf( fp, "%u\n" , &numbElems );

   for( unsigned i = 1; i <= numbElems; i++ )
   {
      TPatternElem elem;
            
      fscanf( 
         fp,
         "%u %f %f %f\n",
         &elem.situation,
         &elem.forces.Fx,
         &elem.forces.Fz,
         &elem.forces.My );

      insert( end(), elem );
   }

   strcpy( name, fileName );
   fclose( fp );
   return 0;
}

int TLearnPattern::SavePattern
(
   const char *fileName
)
{
   TPatternElem elem;
   int   stat;
   FILE *fp;

   fp = fopen( fileName, "wt" );
   
   if( fp == NULL ) 
      return 1;
   
   fprintf( fp, "%u", size() );

   stat = GetFirst( &elem );
   while( !stat )
   {
      unsigned sit = elem.situation;
      fprintf(
         fp,
         "\n%u %f %f %f",
         sit,
         elem.forces.Fx,
         elem.forces.Fz,
         elem.forces.My );
   
      stat = GetNext( &elem );
   }

   strcpy( name, fileName );
   fclose( fp );
   return 0;
}

int TLearnPattern::GetFirst
( 
   TPatternElem *elem 
)
{
   if( size() == 0 )
      return 1;
      
   iter = begin();
   *elem = *iter;
   return 0;
}

int TLearnPattern::GetNext 
( 
   TPatternElem *elem 
)
{
   iter++;

   if( iter == end() )
      return 1;

   *elem = *iter;
   return 0;
}

void TLearnPattern::Insert
(
   const TPatternElem& elem
)
{
   insert( end(), elem );
}

void TLearnPattern::Generate( int numbElem )
{
   TSensor sensor;
   TForces forces;

   CreateNewPattern();

   for( int i = 1; i <= numbElem; i++ )
   {
      TPatternElem elem;
      
      int r = random( 4 );
      
      switch( r )
      {
         case 0:
            elem.forces = sensor.GetDeltaForces( LFACETTOUCH );
            elem.situation = FACETSITUATION;
            break;

         case 1:
            elem.forces = sensor.GetDeltaForces( LONEPOINTTOUCH );
            elem.situation = ONEPOINTSITUATION;
            break;

         case 2:
            elem.forces = sensor.GetDeltaForces( LTWOPOINTTOUCH );
            elem.situation = TWOPOINTSITUATION;
            break;

         case 3:
            elem.forces = sensor.GetDeltaForces( LJAMMINGTOUCH );
            elem.situation = JAMMINGSITUATION;
            break;
      }
      Insert( elem );
   }
}

