// DlgTCP.cpp : implementation file
//

#include "stdafx.h"
#include "DlgTCP.h"



#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


WORD SwapWord (WORD *src)
{
	BYTE tt[2] ;
	BYTE *t = (BYTE *)(src) ;

	tt[1] = t[0] ;
	tt[0] = t[1] ;

	return *((WORD*)tt) ;
}

DWORD SwapDword(void *src)
{
	BYTE tt[4] ;
	BYTE *t = (BYTE *)(src) ;
	
	tt[0] = t[3];
	tt[1] = t[2];
	tt[2] = t[1];
	tt[3] = t[0];

	return *((DWORD*)tt);

}

/////////////////////////////////////////////////////////////////////////////
// CDlgTCP dialog


CDlgTCP::CDlgTCP(CWnd* pParent /*=NULL*/)
	: CDialog(CDlgTCP::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDlgTCP)
	//}}AFX_DATA_INIT
	
	m_bSync6046Time		= FALSE;
	m_bAutoHealthChk	= FALSE;
	m_bAutoSyncStartup	= FALSE;
	m_uiSyncInterval	= 15;

}


void CDlgTCP::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDlgTCP)
	DDX_Control(pDX, IDC_EDIT_SYNCINTERVAL, m_ctrlSyncInterval);
	DDX_Control(pDX, IDC_CHECK_SYNCINTERVAL, m_ctrlCheckSyncInterval);
	DDX_Control(pDX, IDC_TCP_UPDATE, m_ctrlUpdate);
	DDX_Control(pDX, IDC_EDIT_MAXOVERLAP, m_ctrlMaxOverlap);
	DDX_Control(pDX, IDC_EDIT_MAXFILE, m_ctrlMaxFile);
	DDX_Control(pDX, IDC_EDIT_LOGDIR, m_ctrlLogDir);
	DDX_Control(pDX, IDC_CHECK_TIMESYNC, m_ctrlChkTimeSync);
	DDX_Control(pDX, IDC_CHECK_AUTOSYNC, m_ctrlChkAutoSync);
	DDX_Control(pDX, IDC_TCP_SHUTDOWN, m_ctrlShutdown);
	DDX_Control(pDX, IDC_TCP_PORT, m_ctrlPort);
	DDX_Control(pDX, IDC_TCP_IPADDRESS, m_ctrlIpAddress);
	DDX_Control(pDX, IDC_TCP_DISCONNECT, m_ctrlDisconnect);
	DDX_Control(pDX, IDC_TCP_CONNECT, m_ctrlConnect);
	DDX_Control(pDX, IDC_STATUS_LED, m_ctrlStatusLed);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CDlgTCP, CDialog)
	//{{AFX_MSG_MAP(CDlgTCP)
	ON_BN_CLICKED(IDC_TCP_CONNECT, OnTcpConnect)
	ON_BN_CLICKED(IDC_TCP_DISCONNECT, OnTcpDisconnect)
	ON_WM_DESTROY()
	ON_WM_CANCELMODE()
	ON_BN_CLICKED(IDC_CHECK_TIMESYNC, OnCheckTimesync)
	ON_BN_CLICKED(IDC_TCP_SHUTDOWN, OnTcpShutdown)
	ON_BN_CLICKED(IDC_CHECK_AUTOSYNC, OnCheckAutosync)
	ON_BN_CLICKED(IDC_TCP_UPDATE, OnTcpUpdate)
	ON_BN_CLICKED(IDC_CHECK_SYNCINTERVAL, OnCheckSyncinterval)
	ON_EN_CHANGE(IDC_EDIT_SYNCINTERVAL, OnChangeEditSyncinterval)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDlgTCP message handlers

BOOL CDlgTCP::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	m_pMainWnd = (CMy6046DryEndDlg*)AfxGetMainWnd();
	m_pConfig  = &((CMy6046DryEndApp*)AfxGetApp())->m_SystemConfig;
	
	LoadSettings();

	m_ctrlStatusLed.SetLed(CLed::LED_COLOR_RED, CLed::LED_OFF, CLed::LED_ROUND);
	m_ctrlConnect.SetShade(SHS_METAL,8,40,2,RGB(55,255,55));
	m_ctrlDisconnect.SetShade(SHS_METAL,8,40,2,RGB(255,55,55));
	m_ctrlShutdown.SetShade(SHS_METAL, 8,40,2,RGB(155,0,0));
	m_ctrlUpdate.SetShade(SHS_METAL, 8,40,2,RGB(185,185,25));

	m_ctrlSyncInterval.SetLimitText(3);
	m_ctrlSyncInterval.EnableWindow(m_bSyncOnInterval);
	
	m_ctrlLogDir.EnableWindow(FALSE);
	m_ctrlMaxOverlap.EnableWindow(FALSE);
	m_ctrlMaxFile.EnableWindow(FALSE);
	m_ctrlShutdown.EnableWindow(FALSE);
	m_ctrlUpdate.EnableWindow(FALSE);

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CDlgTCP::OnTcpConnect() 
{
	//Get IP address and convert to ASCII
	DWORD temp;
	m_ctrlIpAddress.GetAddress(temp);
	
	
	if((m_bSync6046Time == TRUE) && (temp == 2130706433 /*127.0.0.1*/))
	{
		DWORD result = AfxMessageBox("Enabling Time-Sync while PLC and DVU run on same machine could lead to corrupt system time.  Disable Time Sync?",MB_YESNO,NULL);
		if(result == IDYES)
		{
			m_bSync6046Time = FALSE;
			m_pMainWnd->SetTimeSync(m_bSync6046Time);
			m_ctrlChkTimeSync.SetCheck(m_bSync6046Time);
			return;
		}
	}

	m_dIPAdress = SwapDword((void*)&temp);
	in_addr ad;
    ad.S_un.S_addr = m_dIPAdress;
	char *addrString   = inet_ntoa(ad);
	
	//Get port
	CString port;
	m_ctrlPort.GetWindowText(port);

	//Convert port to ASCII
	m_dPort = atoi(port);

	if(m_dPort == 0 || m_dIPAdress == 0)
	{
		AfxMessageBox("Port or IP Address Error!");
		return;
	}

	if(m_pMainWnd->RemoteConnect(addrString, m_dPort)){
		m_ctrlStatusLed.SetLed(CLed::LED_COLOR_GREEN, CLed::LED_ON, CLed::LED_ROUND);
		m_pMainWnd->AutoPLCSync(m_bSyncOnInterval, m_uiSyncInterval);
		m_ctrlLogDir.EnableWindow(TRUE);
		m_ctrlMaxOverlap.EnableWindow(TRUE);
		m_ctrlMaxFile.EnableWindow(TRUE);
		m_ctrlShutdown.EnableWindow(TRUE);
		m_ctrlUpdate.EnableWindow(TRUE);
		
		m_pConfig->dRemoteAddress = temp;
		m_pConfig->dRemotePort = atoi(port);
		SaveSettings();
	}
	else
		m_ctrlStatusLed.Flash();
		
}

void CDlgTCP::OnTcpDisconnect() 
{
	if(!m_pMainWnd->m_bRemoteConnected)
		return;

	if(AfxMessageBox("Really Disconnect?", MB_YESNO, NULL) == IDYES)
	{
		if(m_pMainWnd->RemoteDisconnect())
		{
			m_ctrlStatusLed.SetLed(CLed::LED_COLOR_RED, CLed::LED_ON, CLed::LED_ROUND);	
			m_ctrlLogDir.EnableWindow(FALSE);
			m_ctrlMaxOverlap.EnableWindow(FALSE);
			m_ctrlMaxFile.EnableWindow(FALSE);
			m_ctrlShutdown.EnableWindow(FALSE);
			m_ctrlUpdate.EnableWindow(FALSE);
		}
	}
}

void CDlgTCP::LoadSettings()
{
	m_pConfig->Open(CSystemConfig::accessRead);
	m_pConfig->Read();
	m_pConfig->Close();

	m_dIPAdress			= m_pConfig->dRemoteAddress;
	m_dPort				= m_pConfig->dRemotePort;
	m_bSync6046Time		= m_pConfig->bSync6046Time;
	m_bSyncOnInterval	= m_pConfig->bSyncInterval;
	m_bAutoSyncStartup	= m_pConfig->bAutoSyncStartup;
	m_uiMaxFileSize		= m_pConfig->uiMaxFileSize;
	m_uiMaxFileOverlap	= m_pConfig->uiMaxFileOverlap;

	m_uiSyncInterval    = m_pConfig->uiSyncIntervalTime;

		
	m_TargetDir.Format("%s", m_pConfig->targetDir );

	CString temp;
	
	m_ctrlIpAddress.SetAddress(m_pConfig->dRemoteAddress);
	
	temp.Format("%d", m_pConfig->dRemotePort);
	m_ctrlPort.SetWindowText(temp);
	
	m_ctrlChkTimeSync.SetCheck(m_bSync6046Time);
	m_ctrlChkAutoSync.SetCheck(m_bAutoSyncStartup);
	m_ctrlCheckSyncInterval.SetCheck(m_bSyncOnInterval);

	temp.Format("%d", m_uiSyncInterval);
	m_ctrlSyncInterval.SetWindowText(temp);
	
	temp.Format("%d", m_uiMaxFileOverlap);
	m_ctrlMaxOverlap.SetWindowText(temp);

	temp.Format("%d", m_uiMaxFileSize);
	m_ctrlMaxFile.SetWindowText(temp);

	temp.Format("%s", m_TargetDir);
	m_ctrlLogDir.SetWindowText(temp);

	UpdateData(FALSE);

}

void CDlgTCP::SaveSettings()
{		
	if(m_pConfig->Open(CSystemConfig::accessWrite)){
		m_pConfig->Save();
		m_pConfig->Close();
	}

}

void CDlgTCP::OnDestroy() 
{
	SaveSettings();
	
	m_ctrlDisconnect.~CxShadeButton();
	m_ctrlConnect.~CxShadeButton();
	m_ctrlShutdown.~CxShadeButton();

	CDialog::OnDestroy();
}

void CDlgTCP::OnCancelMode() 
{
	CDialog::OnCancelMode();
	
	// TODO: Add your message handler code here
	
}

void CDlgTCP::OnCheckTimesync() 
{
	DWORD temp;
	m_ctrlIpAddress.GetAddress(temp);

	if(m_bSync6046Time == FALSE)
	{
		if((m_pMainWnd->m_bRemoteConnected == TRUE) && (temp == 2130706433 /*127.0.0.1*/))
		{
			DWORD result = AfxMessageBox("Enabling Time-Sync while PLC and DVU run on same machine could lead to corrupt system time.  Continue?",MB_YESNO,NULL);
			if(result == IDNO)
			{
				m_bSync6046Time = FALSE;
				m_ctrlChkTimeSync.SetCheck(m_bSync6046Time);
				return;
			}
		}
	}

	m_bSync6046Time = !m_bSync6046Time;
	m_pMainWnd->SetTimeSync(m_bSync6046Time);
	m_pConfig->bSync6046Time = m_bSync6046Time;
	SaveSettings();
}

void CDlgTCP::OnCheckAutosync() 
{
	m_bAutoSyncStartup =  !m_bAutoSyncStartup;
	m_pConfig->bAutoSyncStartup	 = m_bAutoSyncStartup;
	SaveSettings();
}	
		


void CDlgTCP::OnCheckSyncinterval() 
{
	m_bSyncOnInterval = !m_bSyncOnInterval;

	m_ctrlSyncInterval.EnableWindow(m_bSyncOnInterval);

	if(m_bSyncOnInterval)
	{
		CString text;

		m_ctrlSyncInterval.GetWindowText(text);

		if( text.IsEmpty() )
		{
			m_uiSyncInterval = 10;
			text.Format("%d", m_uiSyncInterval);
			m_ctrlSyncInterval.SetWindowText(text);
		}

		m_uiSyncInterval = (UINT)atoi(text);

		if(m_uiSyncInterval < 10)
		{
			m_uiSyncInterval = 10;
			text.Format("%d", m_uiSyncInterval);
			m_ctrlSyncInterval.SetWindowText(text);
		}
	}
	else
	{

	}

	m_pMainWnd->AutoPLCSync(m_bSyncOnInterval, m_uiSyncInterval);
	m_pConfig->bSyncInterval = m_bSyncOnInterval;
	SaveSettings();
}

void CDlgTCP::OnChangeEditSyncinterval() 
{
	
	CString text;
	
	m_ctrlSyncInterval.GetWindowText(text);

	if( text.IsEmpty() )
	{
		//AfxMessageBox("Invalid Sync Interval");
		m_uiSyncInterval = 0;
		text.Format("%d", m_uiSyncInterval);
		m_ctrlSyncInterval.SetWindowText(text);
	}

	m_uiSyncInterval = (UINT)atoi(text);

	m_pConfig->uiSyncIntervalTime = m_uiSyncInterval;
	SaveSettings();

	if(m_bSyncOnInterval)
	{
		m_pMainWnd->AutoPLCSync(m_bSyncOnInterval, m_uiSyncInterval);
	}
	
}


void CDlgTCP::OnTcpShutdown() 
{
	if(!m_pMainWnd->m_bRemoteConnected)
		return;

	UINT result = AfxMessageBox("    Shutdown the Operating System?", MB_YESNOCANCEL, NULL);
	if( result == IDYES)
	{
		m_pMainWnd->RemoteShutdown(1);
		Sleep(200);
		OnTcpDisconnect(); 
	}
	else if(result == IDNO)
	{
		m_pMainWnd->RemoteShutdown(0);
		Sleep(200);
		OnTcpDisconnect();
	}
	else //IDCANCEL
		return;
}

void CDlgTCP::OnTcpUpdate() 
{
	if(m_pMainWnd->m_bRemoteConnected == FALSE)
		return;

	CString temp;

	ULONG oldFileSize = m_uiMaxFileSize;
	ULONG oldOverlap  = m_uiMaxFileOverlap;
	CString oldDir	  = m_TargetDir;

	m_ctrlMaxFile.GetWindowText(temp);
	m_uiMaxFileSize = (ULONG)atof(temp);
	if(m_uiMaxFileSize <= 0)
	{
		AfxMessageBox("Can't have Zero length file");
		m_uiMaxFileSize = oldFileSize;
		temp.Format("%d", m_uiMaxFileSize);
		m_ctrlMaxFile.SetWindowText(temp);
		return;
	}
	if(m_uiMaxFileSize > 4000)
	{
		AfxMessageBox("Current File Size limit is 4GB!");
		m_uiMaxFileSize = 4000;
		temp.Format("%d", m_uiMaxFileSize);
		m_ctrlMaxFile.SetWindowText(temp);
		return;
	}
	m_pConfig->uiMaxFileSize = m_uiMaxFileSize;

	m_ctrlMaxOverlap.GetWindowText(temp);
	m_uiMaxFileOverlap = (ULONG)atof(temp);
	m_pConfig->uiMaxFileOverlap = m_uiMaxFileOverlap;
	

	m_ctrlLogDir.GetWindowText(m_TargetDir);
	if(m_TargetDir.IsEmpty())
	{
		AfxMessageBox("Can't have empty storage Directory");
		m_TargetDir = oldDir;
		m_ctrlLogDir.SetWindowText(m_TargetDir);
		return;
	}
	

	TRACE("LOGGING DIR = %s", m_TargetDir);
	TRACE("Max File Size = %d", m_uiMaxFileSize);


	m_pMainWnd->RemoteLoggingSetup(m_uiMaxFileSize, m_uiMaxFileOverlap);
	
	char *buff = m_TargetDir.GetBuffer(MAX_PATH);
	if(!m_pMainWnd->RemoteSetPath(buff))
	{
		temp.Format("%s", m_pConfig->targetDir);
		m_ctrlLogDir.SetWindowText(temp);
	}
	m_TargetDir.ReleaseBuffer();

	SaveSettings();

	return;
	/*
	if(oldFileSize != m_uiMaxFileSize)
	{	
		if(oldOverlap != m_uiMaxFileOverlap)
		{
			m_pMainWnd->RemoteLoggingSetup(m_uiMaxFileSize, m_uiMaxFileOverlap);
		}
		else
		{
			m_pMainWnd->RemoteLoggingSetup(m_uiMaxFileSize, oldOverlap);
		}
	}
	else if(oldOverlap != m_uiMaxFileOverlap)
	{
		m_pMainWnd->RemoteLoggingSetup(m_uiMaxFileSize, oldOverlap);
	}

	if(oldDir != m_TargetDir)
	{
		char *buff = m_TargetDir.GetBuffer(MAX_PATH);
		m_pMainWnd->RemoteSetPath(buff);
		m_TargetDir.ReleaseBuffer();
	}
	*/

}

BOOL CDlgTCP::PreTranslateMessage(MSG* pMsg) 
{
	if(pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE)
	{
		return TRUE ;
	}
	if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_CANCEL)
	{
		return TRUE ;
	}

	return CDialog::PreTranslateMessage(pMsg);
}


LRESULT CDlgTCP::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	switch(message) 
	{
	case TCP_DISCONNECT: {	
							m_pMainWnd->RemoteDisconnect();
							m_ctrlStatusLed.SetLed(CLed::LED_COLOR_RED, CLed::LED_ON, CLed::LED_ROUND);	
							m_ctrlLogDir.EnableWindow(FALSE);
							m_ctrlMaxOverlap.EnableWindow(FALSE);
							m_ctrlMaxFile.EnableWindow(FALSE);
							m_ctrlShutdown.EnableWindow(FALSE);
							m_ctrlUpdate.EnableWindow(FALSE);
							break; 
						 }

	case TCP_RECONNECT:	 {  OnTcpConnect();break; }

	case LOGGING_ON:	 {	m_ctrlLogDir.EnableWindow(FALSE);break;}

	case LOGGING_OFF:	 {  if(m_pMainWnd->m_bRemoteConnected)
								m_ctrlLogDir.EnableWindow(TRUE);
							break;}

	}

	return CDialog::WindowProc(message, wParam, lParam);
}


void CDlgTCP::UpdateLoggingDirectory( char *loggingDir )
{
	m_ctrlLogDir.SetWindowText(loggingDir);
}
