// LearnDlg.cpp : implementation file
//

#include "stdafx.h"
#include "LearnDlg.h"
#include "ElevatorsApp.h"

#include "TNeuroControlSystem.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CLearnDlg dialog


LearnDlg::LearnDlg()
{
   endDialog  = false;
   timer = 0;
}

LearnDlg::~LearnDlg()
{
}

/////////////////////////////////////////////////////////////////////////////
// CLearnDlg message handlers

UINT LearnDlg::MyControllingFunction( LPVOID pParam )
{
   LearnDlg *dlg = (LearnDlg*)pParam;

   controlSystem->messageHandler( CSM_LEARN_SOLVER, NULL );
   theApp.DoMessageBox("Обучение завершено", MB_OK, 0);

   dlg->endDialog = true;

   return 0;
}

void LearnDlg::init( CDialog* dialog ) 
{
   owner = dialog;

   CEdit *statc = (CEdit*)owner->GetDlgItem(IDC_EDIT_DELTA);
   statc->SetWindowText( "" );

   statc = (CEdit*)owner->GetDlgItem(IDC_EDIT_CYCLE);
   statc->SetWindowText( "" );

   // graph
   CRect rect;
   owner->GetDlgItem(IDC_SOLVER_LEARNING_PIC)->GetWindowRect(rect);
   owner->ScreenToClient(rect);

   Create( WS_VISIBLE|WS_CHILD, rect, owner );

   SetRange( 0, 0.4 );
   SetYUnits( "" );
   SetXUnits( "" );
   SetBackgroundColor(GRAPH_BACK);
   SetGridColor(GRAPH_GRID);
   SetPlotColor(GRAPH_PLOT);
}

void LearnDlg::draw() 
{
   // TODO: Add your message handler code here and/or call default

   CEdit *statc = (CEdit*)owner->GetDlgItem(IDC_EDIT_DELTA);
   
   CString str;
   str.Format( "%10.20f", lastDiff );
   statc->SetWindowText( str );

   AppendPoint( dlgDiff );

   dlgDiff = 0.0;

   CEdit *statc2 = (CEdit*)owner->GetDlgItem(IDC_EDIT_CYCLE);

   int cycle;
   controlSystem->messageHandler( CSM_GET_SOLVER_CYCLE, 
                                  (void*)&cycle );

   str.Format( "%d", cycle );
   statc2->SetWindowText( str );

   if( endDialog )
   {
      owner->KillTimer( timer );
      timer = 0;
      statc->SetWindowText("");
      statc2->SetWindowText("");

      Reset();
   }
   
   owner->GetDlgItem(IDC_SOLVER_LEARNING_PIC)->Invalidate();
   owner->GetDlgItem(IDC_SOLVER_LEARNING_PIC)->UpdateWindow();
}


void LearnDlg::learn() 
{
   // TODO: Add your control notification handler code here
   if( !timer )
   {
      timer = owner->SetTimer( 2, 2000, 0 );

      thread = AfxBeginThread( MyControllingFunction,
                               this );

      ((CButton*)owner->GetDlgItem(IDC_LEARN_BUTTON))->SetWindowText("Stop");
   }
   else
   {
      controlSystem->messageHandler( CSM_SET_SOLVER_STOP_LEARNING, NULL );
      ((CButton*)owner->GetDlgItem(IDC_LEARN_BUTTON))->SetWindowText("Learn");
   }
}
