// mainfrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include <afxpriv.h>          //for WM_IDLEUPDATECMDUI
#include "winaping.h"
#include "constdef.h"

#include "mainfrm.h"
#include "setupdlg.h"
#include "winapdoc.h"
#include "goview.h"

#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
        //{{AFX_MSG_MAP(CMainFrame)
        ON_WM_CREATE()
        ON_MESSAGE(WM_APING_DONE, OnApingDone)    // user msg
        ON_COMMAND(ID_ACTION_GO, OnActionGo)
        ON_COMMAND(ID_ACTION_SETUP, OnActionSetup)
        ON_COMMAND(ID_ACTION_STOP, OnActionStop)
        ON_UPDATE_COMMAND_UI(ID_ACTION_GO, OnUpdateActionGo)
        ON_UPDATE_COMMAND_UI(ID_ACTION_STOP, OnUpdateActionStop)
        ON_UPDATE_COMMAND_UI(ID_ACTION_SETUP, OnUpdateActionSetup)
        //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// arrays of IDs used to initialize control bars

// toolbar buttons - IDs are command buttons
static UINT BASED_CODE buttons[] =
{
        // same order as in the bitmap 'toolbar.bmp'
        ID_ACTION_GO,
        ID_ACTION_STOP,
        ID_ACTION_SETUP,
/*      ID_FILE_NEW,
        ID_FILE_OPEN,
        ID_FILE_SAVE,
                ID_SEPARATOR,
        ID_EDIT_CUT,
        ID_EDIT_COPY,
        ID_EDIT_PASTE,
                ID_SEPARATOR,
        ID_FILE_PRINT,          */
};

static UINT BASED_CODE indicators[] =
{
        ID_SEPARATOR,           // status line indicator
// -------------------------------
// Remove all 3 default indicators
//      ID_INDICATOR_CAPS,
//      ID_INDICATOR_NUM,
//      ID_INDICATOR_SCRL,
};

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame() : pDoc(NULL), pView(NULL), m_running(FALSE)
{
}

CMainFrame::~CMainFrame()
{
  if (pDoc != NULL)
    if (pDoc->aping != NULL) delete pDoc->aping;
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
        if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
                return -1;

        if (!m_wndToolBar.Create(this) ||
                !m_wndToolBar.LoadBitmap(IDR_MAINFRAME) ||
                !m_wndToolBar.SetButtons(buttons,
                  sizeof(buttons)/sizeof(UINT)))
        {
                TRACE0("Failed to create toolbar\n");
                return -1;      // fail to create
        }
        m_wndToolBar.SetWindowText(_T("winaping"));
/* -------------------------------------------------------------------------
// No Status bar display
        if (!m_wndStatusBar.Create(this) ||
                !m_wndStatusBar.SetIndicators(indicators,
                  sizeof(indicators)/sizeof(UINT)))
        {
                TRACE0("Failed to create status bar\n");
                return -1;      // fail to create
        }
------------------------------------------------------------------------- */

        // TODO: Delete these three lines if you don't want the toolbar to
        //  be dockable
        m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
        EnableDocking(CBRS_ALIGN_ANY);
        DockControlBar(&m_wndToolBar);

        // TODO: Remove this if you don't want tool tips
        m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() |
                CBRS_TOOLTIPS | CBRS_FLYBY);

        PostMessage(WM_COMMAND, ID_ACTION_SETUP);

        return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
        // TODO: Add your specialized code here and/or call the base class
//------------------------------------------------------------
// Remove FWS_ADDTOTITLE if you don't want main window resizable
//      cs.style = WS_OVERLAPPED | WS_CAPTION | FWS_ADDTOTITLE
//              | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
//-----------------------------------------------------------------
// Hard code the size for now ....... Do a better way later .......
        cs.cx = 33*13+6;
        cs.cy = 59*7;
        return CFrameWnd::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
//      CFrameWnd::AssertValid();          ????? ASSERT FAILED HERE ??????
}

void CMainFrame::Dump(CDumpContext& dc) const
{
        CFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers

void CMainFrame::OnActionGo()
{
  //----------------------------------------
  //Initial house cleaning work before start
  m_running     = TRUE;
  pDoc->alloctime = 0;
  pDoc->confirmtime = 0;
  pDoc->partner.Empty();
  pDoc->cmcall.Empty();
  pDoc->cmrcmsg.Empty();
  pDoc->stoprunning = FALSE;
  pDoc->buffer = NULL;

  pView->Refresh0();
  CString str = _T("Running...");
  pView->RefreshMsg(str);
  m_start_time = m_start_time.GetCurrentTime();

  //-------------------------------------------------------------------
  //Create object aping (if not exist) and start a new execution thread
  if (pDoc->aping == NULL) pDoc->aping = DEBUG_NEW Aping();

//pDoc->SetTitle((LPCTSTR)pDoc->pingInfo.destination);

//pRunningThread = (Aping*) AfxBeginThread(pDoc->aping->PingIt, (LPVOID)this);
  pRunningThread = (Aping*) AfxBeginThread(pDoc->aping->PingIt, (LPVOID)this,
                                           THREAD_PRIORITY_BELOW_NORMAL);
  if (pRunningThread == NULL) {
    AfxMessageBox("Creating worker thread failed .....");
    PostMessage(WM_COMMAND, ID_APP_EXIT);
    }

}

void CMainFrame::OnActionStop()
{
  pDoc->stoprunning = TRUE;
  CString str = _T("Stopping ....");
  pView->RefreshMsg(str);

}

void CMainFrame::OnActionSetup()
{
  //------------------------------------------------
  // Get and save ptr to Doc & View
  // Safe to do so since we only have 1 doc & 1 view
  if (pDoc == NULL) {
    pDoc  = (CWinapingDoc*) GetActiveDocument();
    pView = (CGoView*) GetActiveView();
    }

  CSetupdlg dlg(pDoc->pingInfo);
  dlg.DoModal();
}

void CMainFrame::OnUpdateActionGo(CCmdUI* pCmdUI)
{
  pCmdUI->Enable(!m_running);

}

void CMainFrame::OnUpdateActionStop(CCmdUI* pCmdUI)
{
  pCmdUI->Enable(m_running);

}

void CMainFrame::OnUpdateActionSetup(CCmdUI* pCmdUI)
{
  pCmdUI->Enable(!m_running);

}

LONG CMainFrame::OnApingDone(UINT a, LONG b) {
  
  SendMessageToDescendants(WM_IDLEUPDATECMDUI, (WPARAM) TRUE);

  CTime     m_end_time = m_end_time.GetCurrentTime();
  CTimeSpan          t = m_end_time - m_start_time;
  CString str = _T("Aping completed.");
  if (pDoc->stoprunning) str = _T("Aping stopped.");
  str += _T(" Total clock time =");
  CString tmp;
  UINT i = t.GetDays();
  if (i>0) { tmp.Format(_T( "%d day"), i); str+=tmp; if (i>1) str+=_T("s"); }
  i = t.GetHours();
  if (i>0) { tmp.Format(_T(" %d hour"), i); str+=tmp; if (i>1) str+=_T("s"); }
  i = t.GetMinutes();
  if (i>0) { tmp.Format(_T(" %d minute"), i); str+=tmp; if (i>1) str+=_T("s"); }
  i = t.GetSeconds();
  tmp.Format(_T(" %d second"), i); str+=tmp; if (i>1) str+=_T("s");

  pView->RefreshMsg(str);
  pDoc->stoprunning = FALSE;

  MessageBeep(0xFFFFFFFF);
  // Moved the setting of m_running to ensure that the start button
  // does not get enabled before the DONE processing is finished.
  m_running = FALSE;
  return 0;
}

