// aping.cpp : implementation file
//

#include "stdafx.h"
#include "constdef.h"
#include "aping.h"

#include "winaping.h"
#include "mainfrm.h"
#include "goview.h"
#include "winapdoc.h"
#include "docpic.h"

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

/////////////////////////////////////////////////////////////////////////////
// aping

Aping::Aping()
{
}

Aping::~Aping()
{
}


UINT Aping::PingIt(LPVOID pParam)
{
  CMainFrame*   pmf  = (CMainFrame*) pParam;
  CWinapingDoc* pDoc = pmf->pDoc;
  long          rc;
  long          itertime;
  BOOL          verifyok;

  rc = DoAllocate(pDoc);              // Go do cminit

  if ((rc <= 0) && (!pDoc->stoprunning))
    pmf->pView->PostMessage(WM_REFRESH, 0, 0);

  if ((rc <= 0) &&  (!pDoc->stoprunning))
    rc = DoExchange(pDoc);           // Go do exchange version/plateform info

  if ((rc == 0) && (!pDoc->stoprunning))
    pmf->pView->PostMessage(WM_REFRESH, 0, 0);

  if ((rc == 0) &&  (!pDoc->stoprunning)) {
    pDoc->buffer = (unsigned char *) malloc(pDoc->pingInfo.packetSize);
    if (pDoc->buffer == NULL) {                          // failed to get buffer
      pDoc->cmcall  = _T("Buffer allocation");
      rc = LAST_MESSAGE_NUM-3;                           // special rc
      }
    else {                                               // Got a buffer
      memset(pDoc->buffer, 0, pDoc->pingInfo.packetSize);
      for (UINT i = 1; i <= pDoc->pingInfo.iterations; i++) {   // loop it
        rc = DoIteration(pDoc, &itertime, &verifyok);    // Go do one iteration
        if ((rc > 0) || (pDoc->stoprunning)) break;
        if (!verifyok) itertime = -itertime;         // flag it if verify failed
        pmf->pView->PostMessage(WM_REFRESH, i, itertime);
        }
      free (pDoc->buffer);
      }
    }

  if (rc != 0) {                       // display any error msg before deallc
    DoTranslate(pDoc, rc);
    pmf->pView->PostMessage(WM_CPICCALL_ERR, 0, 0);
    Sleep(1000);                       // give it a little chance
    }

  rc = DoDeallocate(pDoc);             // Always do cmdeallc

  if (rc != 0) {                       // display deallc error msg if any
    DoTranslate(pDoc, rc);
    pmf->pView->PostMessage(WM_CPICCALL_ERR, 0, 0);
    Sleep(1000);                       // give it a little chance
    }

  pmf->PostMessage(WM_APING_DONE, 0, 0);
  return 0;
}
