//---------------------------------------------------------------------------
#include <vcl\vcl.h>
#pragma hdrstop

#include "Main.h"
#include "Learn.h"
#include "AboutForm.h"
#include "InputParm.h"
#include "Robot.h"
#include "Scene.h"
#include "NeuroCommon.h"
#include "Autolearn.h"
#include "Config.h"
#include "Configur.h"
#include "Pattern.h"
#include "InputNumbElem.h"
#include "Sensor.h"
//---------------------------------------------------------------------------
#pragma link "CSPIN"
#pragma resource "*.dfm"
TMainForm *MainForm;
TMoveMode  mode;

AnsiString typeName[RFINALTOUCH+1];
AnsiString recognizedName[JAMMINGSITUATION+1];

void CommonMouseDown()
{
   MainForm->RecognizeTimer->Enabled = 1;
   MainForm->Timer->Enabled   = 1;
   MainForm->Timer1->Enabled  = 1;
}

void CommonMouseUp()
{
   MainForm->RecognizeTimer->Enabled = 0;
   MainForm->Timer->Enabled   = 0;
   MainForm->Timer1->Enabled  = 0;
}

//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
	: TForm(Owner)
{
   scene.SetWidth( PaintBox1->Width );
   scene.SetHeight( PaintBox1->Height );

   typeName[NOTOUCH]        = "Нет контакта";
   typeName[LSURFACETOUCH]  = "Слева поверхность";
   typeName[RSURFACETOUCH]  = "Справа поверхность";
   typeName[LFACETTOUCH]    = "Слева фаска";
   typeName[RFACETTOUCH]    = "Справа фаска";
   typeName[LONEPOINTTOUCH] = "Слева одноточка";
   typeName[RONEPOINTTOUCH] = "Справа одноточка";
   typeName[LTWOPOINTTOUCH] = "Слева двухточка";
   typeName[RTWOPOINTTOUCH] = "Справа двухточка";
   typeName[LJAMMINGTOUCH]  = "Слева заклинивание";
   typeName[RJAMMINGTOUCH]  = "Справа заклинивание";
   typeName[LFINALTOUCH]    = "Слева завершена";
   typeName[RFINALTOUCH]    = "Справа завершена";

   recognizedName[NOTOUCHSITUATION]  = "Нет контакта";
   recognizedName[FACETSITUATION]    = "Фаска";
   recognizedName[ONEPOINTSITUATION] = "Одноточка";
   recognizedName[TWOPOINTSITUATION] = "Двухточка";
   recognizedName[JAMMINGSITUATION]  = "Заклинивание";

   SetSigmoidType( HYPERTAN ); 
   SetNiuParm( 0.01 );
   SetLimit( 0.0001 ); 
//   SetDSigma( 1 ); 

   config.LoadFromFile( "global.cfg" );
}
//----------------------------------------------------------------------------
void __fastcall TMainForm::FileNew(TObject *Sender)
{
   TInputParmForm* form = new TInputParmForm( MainForm );

   form->ShowModal();

   recognitionSystem.CreateNewSystem( form->GetNumbMiddle() );

   delete form;
}
//----------------------------------------------------------------------------
void __fastcall TMainForm::FileOpen(TObject *Sender)
{
	if (OpenDialog->Execute())
	{
		//---- Add code to open OpenDialog->FileName ----
		recognitionSystem.LoadFromFile( OpenDialog->FileName.c_str() );
	}
}
//----------------------------------------------------------------------------
void __fastcall TMainForm::FileSave(TObject *Sender)
{
	//---- Add code to save current file under current name ----
   char name[MAXPATH];

	strcpy( name, recognitionSystem.GetName() );

	if( name[0] == '\0' )
	   FileSaveAs( Sender );
	else
	   recognitionSystem.SaveToFile( name );
}
//----------------------------------------------------------------------------
void __fastcall TMainForm::FileSaveAs(TObject *Sender)
{
   char name[MAXPATH];
   SaveDialog->FileName = recognitionSystem.GetName();

	if (SaveDialog->Execute())
	{
 		//--- Add code to save current file under SaveDialog->FileName ---
      strcpy( name, SaveDialog->FileName.c_str() );
		recognitionSystem.SaveToFile( name );
	}
}
//----------------------------------------------------------------------------
void __fastcall TMainForm::FileExit(TObject *Sender)
{
	Close();
}
//----------------------------------------------------------------------------
void __fastcall TMainForm::HelpAbout(TObject *Sender)
{
	//---- Add code to show program's About Box ----

   TAboutBox *aboutBox = new TAboutBox( MainForm );

   aboutBox->ShowModal();

   delete aboutBox;
}

//---------------------------------------------------------------------------


void __fastcall TMainForm::TimerTimer(TObject *Sender)
{
   robot.PaintOnCanvas( MainForm->PaintBox1->Canvas, ERASE );

   switch( ControlModeRadioGroup->ItemIndex )
   {
      case 0:
         robot.Move( XYMODE, mode);
         break;

      case 1:
         robot.Move( GRIPMODE, mode);
         break;
   }
   robot.PaintOnCanvas( MainForm->PaintBox1->Canvas, PAINT );
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::UpButtonMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseDown();
   mode = UP;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::UpButtonMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseUp();
   mode = NOMOVE;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::DownButtonMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseDown();
   mode = DOWN;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::DownButtonMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseUp();
   mode = NOMOVE;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::LeftButtonMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseDown();
   mode = LEFT;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::LeftButtonMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseUp();
   mode = NOMOVE;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::RightButtonMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseDown();
   mode = RIGHT;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::RightButtonMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseUp();
   mode = NOMOVE;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ClockWiseButtonMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseDown();
   mode = CLOCKWISE;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ClockWiseButtonMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseUp();
   mode = NOMOVE;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::AntiClockWiseButtonMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseDown();
   mode = ANTICLOCKWISE;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::AntiClockWiseButtonMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   CommonMouseUp();
   mode = NOMOVE;
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::FormPaint(TObject *Sender)
{
   robot.PaintOnCanvas( MainForm->PaintBox1->Canvas, PAINT );
   scene.PaintOnCanvas( MainForm->PaintBox1->Canvas, clWhite );
//   Label1->Caption = typeName[robot.GetRealTouchType()];
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::LearnButtonClick(TObject *Sender)
{
   TPatternElem elem;
   TLearnForm *learnForm = new TLearnForm( MainForm );

//   RecognizeTimer->Enabled = 0;

   learnForm->ShowModal();

   elem.situation = learnForm->GetRealSituation();
   elem.forces = recognitionSystem.GetDeltaForces();
   pattern.Insert( elem );

//   ConvergedLabel->Caption = recognitionSystem.IsConverged();

//   RecognizeTimer->Enabled = 1;

   delete learnForm;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Timer1Timer(TObject *Sender)
{
   MainForm->PaintBox1->Repaint();
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::FormCreate(TObject *Sender)
{
   recognitionSystem.CreateNewSystem( RECOGNNUMBMIDDLENEURONS );   
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::RecognizeTimerTimer(TObject *Sender)
{
   TSituation situation = recognitionSystem.Recognize();
   
   RecognizeLabel->Caption = recognizedName[situation];
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::N2Click(TObject *Sender)
{
   TAutoLearnForm *autoLearnForm = new TAutoLearnForm( MainForm );

   AutoLearnForm = autoLearnForm;
   autoLearnForm->Series1->Clear();

   autoLearnForm->ShowModal();

   AutoLearnForm = NULL;
   delete autoLearnForm;
}
//---------------------------------------------------------------------------



void __fastcall TMainForm::N5Click(TObject *Sender)
{
   TConfigForm *configForm = new TConfigForm(MainForm);

   configForm->ShowModal();

   delete configForm;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::N6Click(TObject *Sender)
{
   char name[MAXPATH];
   SaveConfigDialog->FileName = config.GetName();

	if (SaveConfigDialog->Execute())
	{
 		//--- Add code to save current file under SaveDialog->FileName ---
      strcpy( name, SaveConfigDialog->FileName.c_str() );
		config.SaveToFile( name );
	}
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::N7Click(TObject *Sender)
{
	if (OpenConfigDialog->Execute())
	{
		//---- Add code to open OpenDialog->FileName ----
		config.LoadFromFile( OpenConfigDialog->FileName.c_str() );
	}
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::FormClose(TObject *Sender, TCloseAction &Action)
{
   char name[MAXPATH];
   char namePat[MAXPATH];
	strcpy( name, recognitionSystem.GetName() );
	strcpy( namePat, pattern.GetName() );
   int key;

	if( name[0] == '\0' )
   {
      if( ( key = Application->MessageBox(
            "Сохранить нейросеть?",
            "Макет СРТО на базе нейросети",
            MB_YESNOCANCEL |
            MB_ICONQUESTION |
            MB_DEFBUTTON2 ) ) == IDYES	)
      {
         FileSaveAs( Sender );

         Action = caFree;
      }
      else if( key == IDNO )
         Action = caFree;
      else
         Action = caNone;

//         Close();
   }

	if( namePat[0] == '\0' )
   {
      if( ( key = Application->MessageBox(
            "Сохранить выборку?",
            "Макет СРТО на базе нейросети",
            MB_YESNOCANCEL |
            MB_ICONQUESTION |
            MB_DEFBUTTON2 ) ) == IDYES	)
      {
         N12Click( Sender );

         Action = caFree;
      }
      else if( key == IDNO )
         Action = caFree;
      else
         Action = caNone;

//         Close();
   }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::N11Click(TObject *Sender)
{
   TInputNumbElemForm* form = new TInputNumbElemForm( MainForm );

   form->ShowModal();

   pattern.Generate( form->GetNumbElem() );

   delete form;
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::N9Click(TObject *Sender)
{
	if (OpenPatternDialog->Execute())
	{
		//---- Add code to open OpenDialog->FileName ----
		pattern.LoadPattern( OpenPatternDialog->FileName.c_str() );
	}
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::N12Click(TObject *Sender)
{
   char name[MAXPATH];
   SavePatternDialog->FileName = pattern.GetName();

	if (SavePatternDialog->Execute())
	{
 		//--- Add code to save current file under SaveDialog->FileName ---
      strcpy( name, SavePatternDialog->FileName.c_str() );
		pattern.SavePattern( name );
	}
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::N10Click(TObject *Sender)
{
   char name[MAXPATH];

	strcpy( name, pattern.GetName() );

	if( name[0] == '\0' )
	   N12Click( Sender );
	else
	   pattern.SavePattern( name );
}
//---------------------------------------------------------------------------

