// cpvmmailDlg.cpp : implementation file
//

#include "stdafx.h"
#include "cpvmmDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CCpvmmailDlg dialog

CCpvmmailDlg::CCpvmmailDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CCpvmmailDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CCpvmmailDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDI_VMMAIL);

  m_FormattedMailString = "";
  m_XtraPages = FALSE;
}

void CCpvmmailDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CCpvmmailDlg)
	DDX_Control(pDX, IDC_MAILLIST, m_MailList);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CCpvmmailDlg, CDialog)
	//{{AFX_MSG_MAP(CCpvmmailDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(ID_REFRESH, OnRefresh)
	ON_BN_CLICKED(ID_DISCARD, OnDiscard)
	ON_BN_CLICKED(ID_KEEP, OnKeep)
	ON_BN_CLICKED(ID_REPLY, OnReply)
	ON_WM_CLOSE()
	ON_NOTIFY(NM_CLICK, IDC_MAILLIST, OnClickMaillist)
	ON_BN_CLICKED(ID_REPLYHIST, OnReplyHist)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CCpvmmailDlg message handlers

BOOL CCpvmmailDlg::OnInitDialog()
{
	CDialog::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
	
	// Show splash screen
  CSplashDlg SplashDialog;
  SplashDialog.DoModal();
	
  try {
  	// Call connections
    CConnectionsDLG ConnDialog;
    if ( ConnDialog.DoModal() != IDOK ) {
      EndDialog(0);
      return TRUE;
    }
  
    // Create the Session object using the Connection name from ConnDialog
    char ConnID = ConnDialog.m_ConnName.GetAt(0);
  	m_pECLSession = new ECLSession(ConnID);
    m_pMyApp = (CCVMMailApp *)AfxGetApp();
    m_pMyApp->m_pECLSession = m_pECLSession;
  
  	// Call Login if necessary
    if ( m_pECLSession->GetPS()->SearchText("WELCOME TO IBM GLOBAL SERVICES") != 0 ) {
      for (int i = 0; i < 3; i++) {
        CLoginDlg LoginDialog;
        if ( LoginDialog.DoModal() != IDOK ) {
          EndDialog(0);
          return TRUE;
        }
  
        // Redo if password not valid.  Allow only 3 tries.
        if ( m_pECLSession->GetPS()->SearchText("PASSWORD NOT AUTHORIZED") ) {
          if ( i == 2 ) {
            AfxMessageBox("Maximum number of logon tries exceeded", MB_ICONEXCLAMATION);
      	    CDialog::OnCancel();
            return TRUE;
          }
          else {
            AfxMessageBox("Invalid Password.  Try again.", MB_ICONEXCLAMATION);
            m_pECLSession->GetPS()->SendKeys("logoff[enter]");
            if ( !m_pMyApp->WaitForScreen("WELCOME TO IBM GLOBAL SERVICES", "VM/ESA ONLINE", 500, 50) ) {
              AfxMessageBox("Couldn't get to Welcome screen", MB_ICONEXCLAMATION);
      	      CDialog::OnCancel();
              return TRUE;
            }
            continue;
          }
        }
        else if ( m_pECLSession->GetPS()->SearchText("not in CP directory") ) {
          if ( i == 2 ) {
            AfxMessageBox("Maximum number of logon tries exceeded", MB_ICONEXCLAMATION);
      	    CDialog::OnCancel();
            return TRUE;
          }
          else {
            AfxMessageBox("Invalid ID or Password.  Try again.", MB_ICONEXCLAMATION);
            m_pECLSession->GetPS()->SendKeys("logoff[enter]");
            if ( !m_pMyApp->WaitForScreen("WELCOME TO IBM GLOBAL SERVICES", "VM/ESA ONLINE", 500, 50) ) {
              AfxMessageBox("Couldn't get to Welcome screen", MB_ICONEXCLAMATION);
    	        CDialog::OnCancel();
              return TRUE;
            }
            continue;
          }
        }
  
        // Wait for the Ready; prompt, end if not there
        if ( m_pMyApp->WaitForScreen("Ready;", "RUNNING", 500, 50) ) {
          break;
        }
        else {
          AfxMessageBox("Couldn't get to Ready; prompt", MB_ICONEXCLAMATION);
      	  CDialog::OnCancel();
          return TRUE;
        }
      }
    }
  
    while (TRUE) {
      // Get to Profs mail
      if ( m_pECLSession->GetPS()->SearchText("Ready;") != 0 ) {
        m_pECLSession->GetPS()->SendKeys("openmail[enter]");
        if ( !m_pMyApp->WaitForScreen("ML01", "In-Basket", 500, 50) ) {
          AfxMessageBox("Please go to the emulator and get to a Ready; prompt", MB_ICONEXCLAMATION);
          continue;
        }
        break;
      }
      else if ( m_pECLSession->GetPS()->SearchText("A00") != 0 ) {
        m_pECLSession->GetPS()->SendKeys("[pf2]");
        if ( !m_pMyApp->WaitForScreen("ML01", "In-Basket", 500, 50) ) {
          AfxMessageBox("Please go to the emulator and get to a Ready; prompt", MB_ICONEXCLAMATION);
          continue;
        }
        break;
      }
      else if ( m_pECLSession->GetPS()->SearchText("ML01") == 0 ) {
          AfxMessageBox("Please go to the emulator and get to a Ready; prompt", MB_ICONEXCLAMATION);
          continue;
      }
      else {
        break;
      }
    }
  
    // Initialize the mail list columns
    CRect ListRect;
    m_MailList.GetWindowRect(ListRect);
    int ListWidth = ListRect.Width();
  
    LV_COLUMN lvc;
    lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
  
    lvc.iSubItem = 0;
    lvc.pszText = "Name";
    lvc.cx = ListWidth / 4;
    lvc.fmt = LVCFMT_LEFT;
    m_MailList.InsertColumn(0,&lvc);
  
    lvc.iSubItem = 1;
    lvc.pszText = "Date";
    lvc.cx = ( ListWidth / 4 ) - 5;
    lvc.fmt = LVCFMT_LEFT;
    m_MailList.InsertColumn(1,&lvc);
  
    lvc.iSubItem = 2;
    lvc.pszText = "Subject";
    lvc.cx = ListWidth / 2;
    lvc.fmt = LVCFMT_LEFT;
    m_MailList.InsertColumn(2,&lvc);
  
    // Get handles to my controls
    m_pMailText = (CEdit *)GetDlgItem(IDC_MAILTEXT);
  
    // Populate the list box
    FillMailList();
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CCpvmmailDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CCpvmmailDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (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
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CCpvmmailDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CCpvmmailDlg::OnRefresh() 
{
  try {
	  // Clear the mail text edit box
    m_pMailText->SetWindowText("");

    // Send a VM refresh and then refresh the mail lit
    m_pECLSession->GetPS()->SendKeys("[pf5]");
    m_pMyApp->WaitForInput(500, 50);
    FillMailList();
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }
}

void CCpvmmailDlg::OnDiscard() 
{
  try {
	  // Clear the mail text edit box
    m_pMailText->SetWindowText("");

    // Page down if necessary
    GetToMailPage();
    
	  // Go to line of message and type discard command
    m_pECLSession->GetPS()->SendKeys("dis[enter]", m_MailRow, 2);
    m_pMyApp->WaitForInput(500, 50);
    FillMailList();

    // Get to top if necessary
    if ( m_XtraPages ) {
      m_XtraPages = FALSE;
      m_pECLSession->GetPS()->SendKeys("[pf6]");
      m_pMyApp->WaitForInput(500, 50);
    }

  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }
	
}

void CCpvmmailDlg::OnKeep() 
{
  try {
  	// Clear the mail text edit box
    m_pMailText->SetWindowText("");

    // Page down if necessary
    GetToMailPage();

	  // Go to line of message and type discard command
    m_pECLSession->GetPS()->SendKeys("keep[enter]", m_MailRow, 2);
    m_pMyApp->WaitForInput(500, 50);
    FillMailList();

    // Get to top if necessary
    if ( m_XtraPages ) {
      m_XtraPages = FALSE;
      m_pECLSession->GetPS()->SendKeys("[pf6]");
      m_pMyApp->WaitForInput(500, 50);
    }
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }
	
	
}

void CCpvmmailDlg::OnReply() 
{
CReplyDlg ReplyDlg;

  try {
    // Page down if necessary
    GetToMailPage();

    // Open the mail item
    m_pECLSession->GetPS()->SendKeys("open[enter]", m_MailRow, 2);
    if ( !m_pMyApp->WaitForScreen("V01", "Note", 500, 50) ) {
      AfxMessageBox("Couldn't get to mail text screen", MB_ICONEXCLAMATION);
      EndDialog(0);
      return;
    }

    // Open Reply Dialog
    ReplyDlg.m_ReplyText = "\r\n\r\n";
    ReplyDlg.DoModal();

    // Get to top if necessary
    if ( m_XtraPages ) {
      m_XtraPages = FALSE;
      m_pECLSession->GetPS()->SendKeys("[pf6]");
      m_pMyApp->WaitForInput(500, 50);
    }
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }

}

void CCpvmmailDlg::OnReplyHist() 
{
CReplyDlg ReplyDlg;

  try {
    // Page down if necessary
    GetToMailPage();

    // Open the mail item
    m_pECLSession->GetPS()->SendKeys("open[enter]", m_MailRow, 2);
    if ( !m_pMyApp->WaitForScreen("V01", "Note", 500, 50) ) {
      AfxMessageBox("Couldn't get to mail text screen", MB_ICONEXCLAMATION);
      EndDialog(0);
      return;
    }

	  // Prep reply text with history text
    ReplyDlg.m_ReplyText = "\r\n\r\n";
    ReplyDlg.m_ReplyText = ReplyDlg.m_ReplyText + 
                         "------------------------------------------------------------\r\n" + 
                         "Begining of Original Note Text\r\n" + 
                         "------------------------------------------------------------\r\n" + 
                         m_FormattedMailString + "\r\n" + 
                         "------------------------------------------------------------\r\n" + 
                         "End of Original Note Text\r\n" + 
                         "------------------------------------------------------------\r\n";

    // Open Reply Dialog
    ReplyDlg.DoModal();
	
    // Get to top if necessary
    if ( m_XtraPages ) {
      m_XtraPages = FALSE;
      m_pECLSession->GetPS()->SendKeys("[pf6]");
      m_pMyApp->WaitForInput(500, 50);
    }
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }

}

void CCpvmmailDlg::OnClose() 
{
  delete m_pECLSession;
	
	CDialog::OnClose();
}

void CCpvmmailDlg::OnClickMaillist(NMHDR* pNMHDR, LRESULT* pResult) 
{
CString MailWorkString("");
int     NumRows = 0;
int     GetRow = 2;
BOOL    EndOfNote = FALSE;
int     Row = 5;
int     i;

  try {
	  // Clear the mail text edit box
    m_pMailText->SetWindowText("");
    m_FormattedMailString = "";

	  // Get the index of the mail item
    if ( m_MailList.GetSelectedCount() == 1 ) {
      for ( i = 0; i < m_NumMailMessages; i++ ) {
        if ( m_MailList.GetItemState( i, LVIS_SELECTED ) ) {
          m_MailIndex = i;
          break;
        }
      }
    }
    else {
      return;
    }

    // Get to the right page for the mail item
    GetToMailPage();

    // Open the mail item
    m_pECLSession->GetPS()->SendKeys("open[enter]", m_MailRow, 2);
    if ( !m_pMyApp->WaitForScreen("V01", "Note", 500, 50) ) {
      AfxMessageBox("Couldn't get to mail text screen", MB_ICONEXCLAMATION);
      EndDialog(0);
      return;
    }

    // Get mail text
    while (!EndOfNote) {
      char   TempString[1502];

      // After the 1st page, the last line of every page is the first line
      // on the next page.  We need to skip the first line after the first page.
      if ( NumRows >= 19 ) {
        GetRow = 3;
      }

      // Get the text and add it to the big mail string
      m_pECLSession->GetPS()->GetScreenRect(TempString, sizeof(TempString), GetRow, 2, 20, 80);
      MailWorkString = MailWorkString + TempString;

      // Check for end of note, if so, chop of the end of note string and
      // keep track of how many rows on last page.
      int EndPosInPS = m_pECLSession->GetPS()->SearchText( "E N D  O F  N O T E", 1, 1 );
      if ( EndPosInPS != 0 ) {
        int EndPosInText = MailWorkString.Find( "E N D  O F  N O T E" );
        MailWorkString = MailWorkString.Left(EndPosInText - 1);
        EndOfNote = TRUE;

        int EndRow = m_pECLSession->GetPS()->ConvertPosToRow(EndPosInPS);
        NumRows+=( EndRow - 1 );
      }
      // If not at end of note, get the whole page then page down, keeping
      // track of a full page of rows.
      else {
        NumRows+=19;

        m_pECLSession->GetPS()->SendKeys("[pf8]");
        m_pMyApp->WaitForInput(500, 50);
      }
    }

    // Parse the big glob of email text that we got into row/cols
    for ( i = 0; i < NumRows; i++ ) {
      m_FormattedMailString = m_FormattedMailString + MailWorkString.Mid( (i * (78 + 1)), 78);
      m_FormattedMailString = m_FormattedMailString + "\r\n";
    }

    // Put the text in the mail text edit box
    m_pMailText->SetWindowText(m_FormattedMailString);

    // Get back out the the mail list screen
    m_pECLSession->GetPS()->SendKeys("[pf12]");
    if ( !m_pMyApp->WaitForScreen("ML01", "In-Basket", 500, 50) ) {
      AfxMessageBox("Couldn't get to mail screen", MB_ICONEXCLAMATION);
      EndDialog(0);
      return;
    }

    // Get to top if necessary
    if ( m_XtraPages ) {
      m_XtraPages = FALSE;
      m_pECLSession->GetPS()->SendKeys("[pf6]");
      m_pMyApp->WaitForInput(500, 50);
    }
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }
	
	*pResult = 0;
}

void CCpvmmailDlg::FillMailList()
{
ULONG   PosForNumItems;
char    NumItemString[5];
ULONG   Row = 5;
BOOL    XtraPages = FALSE;

  try {
    // Clear the mail list control
    m_MailList.DeleteAllItems();

    // Get the number of mail messages 
    PosForNumItems = m_pECLSession->GetPS()->SearchText("of");
    m_pECLSession->GetPS()->GetScreen(NumItemString, sizeof(NumItemString), PosForNumItems + 3, 81 - PosForNumItems + 3, TextPlane);
    m_NumMailMessages = atoi(NumItemString);

    // Get the text we want to put in our list view and add it
    for ( int i = 0; i < m_NumMailMessages; i++ ) {
      char Name[19], Date[17], Subject[71];

      m_MailList.InsertItem(i, "");

      m_pECLSession->GetPS()->GetScreenRect(Name, sizeof(Name), Row, 10, Row, 27, TextPlane);
      m_MailList.SetItemText(i, 0, Name);
      m_pECLSession->GetPS()->GetScreenRect(Date, sizeof(Date), Row, 65, Row, 80, TextPlane);
      m_MailList.SetItemText(i, 1, Date);
      m_pECLSession->GetPS()->GetScreenRect(Subject, sizeof(Subject), Row + 1, 11, Row + 1, 80, TextPlane);
      m_MailList.SetItemText(i, 2, Subject);

      if ( ( ( i + 1 ) % 8) == 0 ) {
        XtraPages = TRUE;
        m_pECLSession->GetPS()->SendKeys("[pf8]");
        m_pMyApp->WaitForInput(500, 50);

        Row = 5;
      }
      else {
        Row = Row + 2;
      }
      
    }

    if (XtraPages) {
      m_pECLSession->GetPS()->SendKeys("[pf6]");
      m_pMyApp->WaitForInput(500, 50);
    }
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }

  return;	
}

void CCpvmmailDlg::GetToMailPage()
{
int     NumPages;

  // Page Down if necessary
  if ( ( m_MailIndex + 1 ) > 8 ) {
    m_XtraPages = TRUE;
    NumPages = ( m_MailIndex + 1 ) / 8;
    m_MailRow = ( ( 2 * m_MailIndex ) % 8 ) + 5;
    for ( int i = 0; i < NumPages; i++ ) {
      m_pECLSession->GetPS()->SendKeys("[pf8]");
      m_pMyApp->WaitForInput(500, 50);
    }
  }
  else {
    m_MailRow = ( m_MailIndex * 2 ) + 5;;
  }

  return;
}
