
// MBARI_TestDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MBARI_Test.h"
#include "MBARI_TestDlg.h"
#include "afxdialogex.h"
#include "struct.h"
#include "defines.h"
#include "stdlib.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CMBARI_TestDlg dialog
CMBARI_TestDlg::CMBARI_TestDlg( CWnd* pParent /*=NULL*/ ) :
	  CDialogEx				( CMBARI_TestDlg::IDD, pParent )
	, m_pCTD_TCP			( NULL )
	, m_pCTD_TCP2			( NULL )
	, m_pTimeSync			( NULL )
	, m_bCTDState1			( false )
	, m_bCTDState2			( false )
	, m_bINUState			( false )
	, m_bFirstEntry		( true )
	, m_bStartup			( true )
	, m_strTimeZDA			(_T(""))
	, m_strCTD				(_T(""))
	, m_strCTDPort1		(_T(""))
	, m_strCTDPort2		(_T(""))
	, m_strZDAPort1		(_T(""))
	, m_strZDAPort2		(_T(""))
	, m_strCTD_TEMPC		(_T(""))
	, m_ForceCTD_C			( 0.0f )
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	memset( m_LastMessage, 0, Status::MSG_SIZE );
}

void CMBARI_TestDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST1, m_StatusListBox);
	DDX_Control(pDX, IDC_PORTLIST, m_PortList);
	DDX_Control(pDX, IDC_IPADDRESS1, m_IPAddress);
	DDX_Control(pDX, IDC_HEADLIST, m_HeadList);
	DDX_Text(pDX, IDC_TIME_STR, m_strTimeZDA);
	DDX_Text(pDX, IDC_CTD_STR, m_strCTD);
	DDX_Control(pDX, IDC_HEADLIST2, m_HeadList2);
	DDX_Control(pDX, IDC_IPADDRESS2, m_IPAddress2);
	DDX_Text(pDX, IDC_EDIT_CTD_PORT1, m_strCTDPort1);
	DDX_Text(pDX, IDC_EDIT_CTD_PORT2, m_strCTDPort2);
	DDX_Text(pDX, IDC_EDIT_ZDA_PORT1, m_strZDAPort1);
	DDX_Text(pDX, IDC_EDIT_ZDA_PORT2, m_strZDAPort2);
	DDX_Text(pDX, IDC_EDIT_CTD_TEMP_C, m_strCTD_TEMPC);
	DDX_Control(pDX, IDC_CHECK1, m_chkForceCTD);
}

BEGIN_MESSAGE_MAP(CMBARI_TestDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDCANCEL3, &CMBARI_TestDlg::OnBnClickedCTD_TCP)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDCANCEL7, &CMBARI_TestDlg::OnBnClickedTimeSyncTCP)

	ON_WM_CLOSE()
	ON_MESSAGE(WM_QUIT, OnExit)
 	ON_MESSAGE(WM_CLOSE, OnExit)

	ON_CBN_SELCHANGE(IDC_HEADLIST, &CMBARI_TestDlg::OnCbnSelchangeHeadlist)
END_MESSAGE_MAP()

BOOL CMBARI_TestDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// set status timer
	SetTimer( 1, 250, NULL );	

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMBARI_TestDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}

	// system init
	bool bOK = true;
	if( m_bStartup )
	{
		m_bStartup = false;

		m_pStatus = new Status();
		if( !m_pStatus )
		{
			AfxMessageBox( "ERROR: Initializing Status Window" );
			bOK = false;
		}
		else
		{
			m_pStatus->PrintStatus( Status::COLOR_ERROR, "3D at Depth MBARI Simulation Tool\n" );

			m_strCTDPort1 = "2009";
			m_strCTDPort2 = "2009";
			m_strZDAPort1 = "2007";
			m_strZDAPort2 = "2007";
			m_strCTD_TEMPC = "10.0";
			UpdateData( FALSE );

			SendDlgItemMessage ( IDC_HEADLIST, CB_ADDSTRING, 0, (LPARAM)"Disabled" );
			SendDlgItemMessage ( IDC_HEADLIST, CB_ADDSTRING, 0, (LPARAM)"Local" );
			SendDlgItemMessage ( IDC_HEADLIST, CB_ADDSTRING, 0, (LPARAM)"Head 1" );
			m_HeadList.SetCurSel( 2 );
			m_IPAddress.SetAddress( 192,168,168,130 );

			SendDlgItemMessage ( IDC_HEADLIST2, CB_ADDSTRING, 0, (LPARAM)"Disabled" );
			SendDlgItemMessage ( IDC_HEADLIST2, CB_ADDSTRING, 0, (LPARAM)"Local" );
			SendDlgItemMessage ( IDC_HEADLIST2, CB_ADDSTRING, 0, (LPARAM)"Head 2" );
			m_HeadList2.SetCurSel( 2 );
			m_IPAddress2.SetAddress( 192,168,168,131 );

			m_pCTD_TCP  = new CTD_TCP( m_pStatus );
			m_pCTD_TCP2 = new CTD_TCP( m_pStatus );
			if( !m_pCTD_TCP || !m_pCTD_TCP2 )
			{
				m_pStatus->PrintStatus( Status::COLOR_ERROR, "ERROR: Initializing CTD_TCP object\n" );
				bOK = false;
			}

			m_pTimeSync = new TimeSync( m_pStatus );
			if( !m_pTimeSync )
			{
				m_pStatus->PrintStatus( Status::COLOR_ERROR, "ERROR: Initializing Time Sync object\n" );
				bOK = false;
			}
			else
			{
				CUIntArray* ports = new CUIntArray();
				m_pTimeSync->EnumerateSerialPorts(*ports);
				UINT portNum = 0;
				for (int i=0; i<ports->GetCount(); i++)
				{
					portNum = ports->GetAt(i);
					CString str;
					str.Format( "COM%d:", portNum );
					SendDlgItemMessage ( IDC_PORTLIST, CB_ADDSTRING, 0, (LPARAM)str.GetBuffer() );
				}
				m_PortList.SetCurSel( 0 );
			} 

			UpdateData( TRUE );
		}

		if( bOK ) {	m_pStatus->PrintStatus( "Initialization Successful\n" ); }
		else      {	m_pStatus->PrintStatus( "Initialization Failed\n" ); }
	}


}


HCURSOR CMBARI_TestDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CMBARI_TestDlg::OnTimer(UINT_PTR nIDEvent)
{
	if( nIDEvent == 1  ) 
	{
		UpdateStatus();
 
		if( m_pTimeSync )
		{
			char buf[128];
			m_pTimeSync->GetZDAStr( buf );
			m_strTimeZDA = buf;
			//UpdateData( FALSE );
		}
 
		if( m_pCTD_TCP && m_bCTDState1 )
		{
			float waterTemp_C				= 0.0f;
			float waterSalinity_psu		= 0.0f;
			float waterPressure_dbar	= 0.0f;
			m_pCTD_TCP->GetCTD( &waterTemp_C, &waterSalinity_psu, &waterPressure_dbar );
			m_strCTD.Format("%.1f C, %.1f dbar, %.1f psu", waterTemp_C, waterPressure_dbar, waterSalinity_psu );
			GetDlgItem(IDC_CTD_STR)->SetWindowTextA(m_strCTD);// UpdateData(FALSE);
		}
		if( m_pCTD_TCP2 && m_bCTDState2 )
		{
			float waterTemp_C				= 0.0f;
			float waterSalinity_psu		= 0.0f;
			float waterPressure_dbar	= 0.0f;
			m_pCTD_TCP2->GetCTD( &waterTemp_C, &waterSalinity_psu, &waterPressure_dbar );
			m_strCTD.Format("%.1f C, %.1f dbar, %.1f psu", waterTemp_C, waterPressure_dbar, waterSalinity_psu );
			GetDlgItem(IDC_CTD_STR)->SetWindowTextA(m_strCTD);
		}	
 
 
	}
	CDialog::OnTimer(nIDEvent);
}

void CMBARI_TestDlg::UpdateStatus()
{
	if( !m_pStatus ) return;

	char nextMessage[Status::MSG_SIZE];
	memset( nextMessage, 0, Status::MSG_SIZE );
	int nextColor = 0;

	while( m_pStatus->MessageAvailable() )
	{
		if( m_pStatus->GetNextMessage( nextMessage, &nextColor ) )
		{
			int currentCount = m_StatusListBox.GetCount();

			// don't let the list get too big...
			if (currentCount >= Status::REPORTER_LIST_MAX) { m_StatusListBox.DeleteString(0); }

			// check if we are appending to last item
			// check for a new line, or append to previous
			bool bAppend = true;
			if( m_bFirstEntry) { bAppend = false; }
			else
			{
				int len = strlen( m_LastMessage );
				if( len > 0 )
				{
					if( m_LastMessage[ len-1 ] == '\n' )
					{ bAppend = false; }
					if( m_LastMessage[ len-1 ] == '\r' )
					{ bAppend = false; }
				}
				else { bAppend = false; }
			}

			char sttemp[Status::MSG_SIZE*2];
			if( bAppend )
			{
				//int i = m_MsgCnt;
				m_LastMessage[Status::MSG_SIZE-1] = 0;
				nextMessage  [Status::MSG_SIZE-1] = 0;
				memset( sttemp, 0, Status::MSG_SIZE *2 );
				sprintf_s( sttemp, "%s %s", m_LastMessage, nextMessage );
				sttemp[Status::MSG_SIZE-1] = 0;
				m_StatusListBox.DeleteString( currentCount-1 );
				if (m_StatusListBox.AddString( sttemp, m_pStatus->GetColorRef( nextColor ) ) < 0) { m_StatusListBox.DeleteString(0); }
				strcpy_s( m_LastMessage, Status::MSG_SIZE, sttemp );
			}
			else
			{
				if (m_StatusListBox.AddString( nextMessage, m_pStatus->GetColorRef( nextColor ) ) < 0) { m_StatusListBox.DeleteString(0); }
				strcpy_s( m_LastMessage, Status::MSG_SIZE, nextMessage );
			}
			m_bFirstEntry = false;

			int topIndex = currentCount - Status::REPORTER_LIST_VISIBLE + 1;
			if( topIndex < 0 ) { topIndex = 0; }
			m_StatusListBox.SetTopIndex( topIndex );
			m_StatusListBox.SetHorizontalExtent( 500 );
		}
	}
}


void CMBARI_TestDlg::OnCbnSelchangeHeadlist()
{
	if( m_HeadList.GetCurSel() == 0 ) // disabled
	{
		m_IPAddress.SetAddress( 0,0,0,0 );
	}
	else if( m_HeadList.GetCurSel() == 1 ) // local
	{
		m_IPAddress.SetAddress( 127,0,0,1 );
	}
	else if( m_HeadList.GetCurSel() == 2 )
	{
		m_IPAddress.SetAddress( 192,168,168,130 );
	}
	else
	{
		m_IPAddress.SetAddress( 192,168,168,131 );
	}
	//UpdateData( FALSE );
}


void CMBARI_TestDlg::OnBnClickedTimeSyncTCP()
{
	GetSettings();

	//UpdateData( FALSE /*bSaveAndValidate = 1*/ );
	bool bOK;
	m_pStatus->PrintStatus( "Initializing Time Sync Subsystem ...\n" );
	CString strCommPort;
#ifdef SIM_UDP_SERIAL
	strCommPort = "";
#else
	m_PortList.GetLBText( (int)m_PortList.GetCurSel(), strCommPort );
#endif

	if( m_HeadList. GetCurSel() == 0 ) { m_strIP1 = ""; }
	if( m_HeadList2.GetCurSel() == 0 ) { m_strIP2 = ""; }

	bOK = m_pTimeSync->Initialize( strCommPort.GetBuffer(), m_strIP1.GetBuffer(), m_ZDAPort1, m_strIP2.GetBuffer(), m_ZDAPort2 );
}


void CMBARI_TestDlg::OnBnClickedCTD_TCP()
{
	GetSettings();

	if( m_pCTD_TCP )
	{	
		if( m_HeadList.GetCurSel() == 0 ) // disabled
		{
			m_bCTDState1 = false;
		}
		else 
		{
			if( m_pCTD_TCP->Initialize( m_strIP1.GetBuffer(),  m_CTDPort1 ) )
			{
				if(  m_chkForceCTD.GetCheck() ) { m_pCTD_TCP->ForceTempC( m_ForceCTD_C ); }

				m_bCTDState1 = !m_bCTDState1;
				m_pCTD_TCP->SetState( m_bCTDState1 );
			}
		}
	}

	if( m_pCTD_TCP2 )
	{	
		if( m_HeadList2.GetCurSel() == 0 ) // disabled
		{
			m_bCTDState2 = false;
		}
		else 
		{
			if( m_pCTD_TCP2->Initialize( m_strIP2.GetBuffer(),  m_CTDPort2 ) )
			{
				if(  m_chkForceCTD.GetCheck() ) { m_pCTD_TCP2->ForceTempC( m_ForceCTD_C ); }

				m_bCTDState2 = !m_bCTDState2;
				m_pCTD_TCP2->SetState( m_bCTDState2 );
			}
		}
	}

}

void CMBARI_TestDlg::GetSettings()
{
	UpdateData( TRUE /*bSaveAndValidate = 1*/ );
	m_IPAddress .GetWindowTextA( m_strIP1 );
	m_IPAddress2.GetWindowTextA( m_strIP2 );

	m_CTDPort1   = atoi( m_strCTDPort1.GetBuffer() );
	m_CTDPort2   = atoi( m_strCTDPort2.GetBuffer() );
	m_ZDAPort1   = atoi( m_strZDAPort1.GetBuffer() );
	m_ZDAPort2   = atoi( m_strZDAPort2.GetBuffer() );
	m_ForceCTD_C = (float)atof( m_strCTD_TEMPC.GetBuffer() );
}


LRESULT CMBARI_TestDlg::OnExit(WPARAM wParam, LPARAM lParam )
{
	return (LRESULT)1;
}

void CMBARI_TestDlg::OnClose()
{
	if( m_pTimeSync ) delete m_pTimeSync;
	CDialog::OnClose();
}

