// cpdslistDlg.cpp : implementation file
//

#include "stdafx.h"
#include "cpdslist.h"
#include "cpdsdlg.h"
#include "splash.h"
#include "dsnldlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CDSListDlg dialog

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

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

BEGIN_MESSAGE_MAP(CDSListDlg, CDialog)
	//{{AFX_MSG_MAP(CDSListDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_REFRESHDS, OnRefreshds)
	ON_NOTIFY(NM_CLICK, IDC_DSLIST, OnClickDslist)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDSListDlg message handlers

BOOL CDSListDlg::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();
	
  // Get handles to my controls
  m_pDSContents = (CEdit *)GetDlgItem(IDC_DSCONTENTS);
  m_pDSList = (CListCtrl *)GetDlgItem(IDC_DSLIST);
  
  try {
  	// Call connections
    CConnectionsDLG ConnDialog;
    if ( ConnDialog.DoModal() != IDOK ) {
      EndDialog(0);
      return TRUE;
    }
  
    // Create the Session object using the Connection from connection dialog
    char ConnID = ConnDialog.m_ConnName.GetAt(0);
  	m_pECLSession = new ECLSession(ConnID);
    m_pMyApp = (CDSListApp *)AfxGetApp();
    m_pMyApp->m_pECLSession = m_pECLSession;
  
    // Initialize the mail list columns
    CRect ListRect;
    m_pDSList->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 / 2;
    lvc.fmt = LVCFMT_LEFT;
    m_pDSList->InsertColumn(0,&lvc);
  
    lvc.iSubItem = 1;
    lvc.pszText = "Message";
    lvc.cx = ( ListWidth / 4 ) - 5;
    lvc.fmt = LVCFMT_LEFT;
    m_pDSList->InsertColumn(1,&lvc);
  
    lvc.iSubItem = 2;
    lvc.pszText = "Volume";
    lvc.cx = ListWidth / 4;
    lvc.fmt = LVCFMT_LEFT;
    m_pDSList->InsertColumn(2,&lvc);
  
    // Get to the DS List screen
    if ( !GetToISPF() ) {
      EndDialog(0);
      return TRUE;
    }

    // Populate the list box
    FillDSList();
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }

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

// 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 CDSListDlg::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 CDSListDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDSListDlg::FillDSList() 
{
ULONG   PosForNumItems;
char    NumItemString[5];
ULONG   Row = 8;
BOOL    XtraPages = FALSE;
int     j = 1;

  try {
    // Clear the mail list control
    m_pDSList->DeleteAllItems();

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

    // Get the text we want to put in our list view and add it
    for ( int i = 0; i < m_NumDS; i++ ) {
      char Name[54], Message[17], Volume[9];
      CString CleanName;

      m_pDSList->InsertItem(i, "");

      m_pECLSession->GetPS()->GetScreenRect(Name, sizeof(Name), Row, 2, Row, 54, TextPlane);
      CleanName = Name;
      CleanName.TrimLeft();
      m_pDSList->SetItemText(i, 0, CleanName);
      m_pECLSession->GetPS()->GetScreenRect(Message, sizeof(Message), Row, 56, Row, 71, TextPlane);
      m_pDSList->SetItemText(i, 1, Message);
      m_pECLSession->GetPS()->GetScreenRect(Volume, sizeof(Volume), Row, 73, Row, 80, TextPlane);
      m_pDSList->SetItemText(i, 2, Volume);

      if ( j == 17 ) {
        XtraPages = TRUE;
        m_pECLSession->GetPS()->SendKeys("[pf8]");
        m_pMyApp->WaitForInput(500, 50);
        j = 1;
        Row = 8;
      }
      else {
        Row++;
        j++;
      }
      
    }

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

  return;
}

BOOL CDSListDlg::GetToISPF() 
{

  try {
    // User must be at the ISPF main screen, DSList menu screen, or
    // DSList screen for this sample to work.
    while (TRUE) {
      // At main ISPF menu
      if ( m_pECLSession->GetPS()->SearchText( "ISPF Primary Option Menu" ) != 0 ) {
        // Get to the utility menu screen
        m_pECLSession->GetPS()->SendKeys("3[enter]");
        if ( !m_pMyApp->WaitForScreen("Utility Selection Panel", "Option ===>", 500, 50) ) {
          AfxMessageBox("Couldn't get to Utility Selection Panel", MB_ICONEXCLAMATION);
          return FALSE;
        }
      }
      // At utility selection menu
      else if ( m_pECLSession->GetPS()->SearchText( "Utility Selection Panel" ) != 0 ) {
        // Get to the dataset menu screen
        m_pECLSession->GetPS()->SendKeys("4[enter]");
        if ( !m_pMyApp->WaitForScreen("Data Set List Utility", "Option ===>", 500, 50) ) {
          AfxMessageBox("Couldn't get to DS List Menu", MB_ICONEXCLAMATION);
          return FALSE;
        }
      }
      // At DSList menu
      else if ( m_pECLSession->GetPS()->SearchText( "Data Set List Utility" ) != 0 ) {
        // Get the dsname level from the user
        CDSNLevelDlg DSNameDlg;
        DSNameDlg.DoModal();

        // Get the dataset list name level from the user
        CString DSNLevel = DSNameDlg.m_DSNLevel;

        // User didn't give us a Dsname Level
        if ( DSNLevel.IsEmpty() ) {
          m_pECLSession->GetPS()->SendKeys("[enter]");
        }
        // Clear the Dsname Level field and enter what the user gave us
        else {
          m_pECLSession->GetPS()->SetText("                                            ", 10, 24);
          m_pECLSession->GetPS()->SetText(DSNLevel, 10, 24);
          m_pECLSession->GetPS()->SendKeys("[enter]");
        }

        // Wait for the DL List screen
        if ( !m_pMyApp->WaitForScreen("DSLIST -", "Data Set", 500, 50) ) {
          AfxMessageBox("Couldn't get to DS List", MB_ICONEXCLAMATION);
          return FALSE;
        }
      }
      // We're at the dataset list
      else if ( m_pECLSession->GetPS()->SearchText( "DSLIST -" ) != 0 ) {
        // Make sure we're at the top of the DSList
        m_pECLSession->GetPS()->SendKeys("top[enter]", 4, 15);
        m_pMyApp->WaitForInput(500, 50);
        break;
      }
      // Make user go to screen
      else {
        if ( IDCANCEL == AfxMessageBox("Please get to ISPF Primary Option Menu, Data Set List Utility screen, or DSLIST screen.", MB_ICONEXCLAMATION | MB_OKCANCEL) ) {
          return FALSE;
        }
      }
    }
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
    return FALSE;
  }

  return TRUE;
}

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

void CDSListDlg::OnRefreshds() 
{
	  // Clear the edit box
    m_pDSContents->SetWindowText("");

    // Make sure we're at the top of the DSList
    m_pECLSession->GetPS()->SendKeys("top[enter]", 4, 15);
    m_pMyApp->WaitForInput(500, 50);

    // Populate the list box
    FillDSList();

}

void CDSListDlg::OnClickDslist(NMHDR* pNMHDR, LRESULT* pResult) 
{
int IndexOnPanel;
int NumPages;
int DSIndex;
int i;
CString WorkString(""), FormattedString("");;

  try {  
    char   TempString[1521];  // 19 rows of 80 columns + NULL character

	  // Get the index of the dataset clicked
    if ( m_pDSList->GetSelectedCount() == 1 ) {
      for ( i = 0; i < m_NumDS; i++ ) {
        if ( m_pDSList->GetItemState( i, LVIS_SELECTED ) ) {
          DSIndex = i + 1;
          break;
        }
      }
    }
    else {
      return;
    }

    // Page down if necessary
    if ( DSIndex > 17 ) {
      NumPages = DSIndex / 17;
      IndexOnPanel = DSIndex % 17;
      for ( i = 0; i < NumPages; i++ ) {
        m_pECLSession->GetPS()->SendKeys("[pf8]");
        m_pMyApp->WaitForInput(500, 50);
      }
    }
    else {
      IndexOnPanel = DSIndex;
    }

    // Get to the dataset and open it
    m_pECLSession->GetPS()->SendKeys("b[enter]", IndexOnPanel + 7, 2 );
    // Extra long wait to allow for archived datasets
    if ( !m_pMyApp->WaitForScreen("BROWSE", "Top of Data", 500, 1000) ) {
      AfxMessageBox("Couldn't get to dataset contents.  Dataset may be archived", MB_ICONEXCLAMATION);
      return;
    }

    // Get the text
    m_pECLSession->GetPS()->GetScreenRect(TempString, sizeof(TempString), 6, 1, 24, 80);
    WorkString = TempString;

    // Parse the big glob of text that we got into row/cols
    for ( int i = 0; i < 19; i++ ) {
      FormattedString = FormattedString + WorkString.Mid( (i * 80), 80);
      FormattedString = FormattedString + "\r\n";
    }

    // Put the text in the edit box
    m_pDSContents->SetWindowText(FormattedString);

    // Get back to the dataset list
    m_pECLSession->GetPS()->SendKeys("[pf3]");
    if ( !m_pMyApp->WaitForScreen("DSLIST -", "Data Set", 500, 50) ) {
      AfxMessageBox("Couldn't get to DS List", MB_ICONEXCLAMATION);
      return;
    }

    // Make sure we're at the top of the DSList
    m_pECLSession->GetPS()->SendKeys("top[enter]", 4, 15);
    m_pMyApp->WaitForInput(500, 50);
  }
  catch (ECLErr Err) {
    AfxMessageBox(Err.GetMsgText(), MB_ICONEXCLAMATION);
  }
	
	*pResult = 0;
}
