// MDIChildExecute.cpp : implementation file
//

#include "stdafx.h"
#include "AKAssms.h"
#include "MDIChildExecute.h"
#include "AKAssmsViewEditSQL.h"
#include "AKAssmsListView.h"

#include "AKAssmsDoc.h"
#include "AKAssmsView.h"

#include "CListCtrl_Ext.h"

#define MSG_SQLselect       _T("SQLselect")
#define MSG_SQLselectItem   _T("SQLselectItem")

// CMDIChildExecute

IMPLEMENT_DYNCREATE(CMDIChildExecute, CMDIChildWndEx)

CMDIChildExecute::CMDIChildExecute()
{
    m_bInitSplitter = false;
}

CMDIChildExecute::~CMDIChildExecute()
{
}

BOOL
CMDIChildExecute::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
//__super::OnCreateClient(lpcs,pContext);
//if(1)return TRUE;
	  //m_wndSplitter.Create ( this,
		//                              2, 1,       // TODO: adjust the number of rows, columns
		//                              CSize(10, 10),  // TODO: adjust the minimum pane size
		//                              pContext);
	//calculate client size
	CRect cr;
	GetWindowRect( &cr );
	CSize size(cr.Width(), cr.Height()/2);

	
	// Create the main splitter with 2 rows and 1 column
	if ( !m_wndSplitter.CreateStatic( this, 2, 1 ) )
	{
		MessageBox( "Error setting up m_mainSplitter", "ERROR", MB_OK | MB_ICONERROR );
		return FALSE;
	}

	// The views for each pane must be created 
	if ( !m_wndSplitter.CreateView( 0, 0, RUNTIME_CLASS(CAKAssmsViewEditSQL),
		size, pContext ) )
	{
		MessageBox( "Error setting up splitter CAKAssmsViewEditSQL view", "ERROR", MB_OK | MB_ICONERROR );
		return FALSE;
	}

  pContext->m_pNewViewClass = RUNTIME_CLASS(CAKAssmsListView);
	if ( !m_wndSplitter.CreateView( 1, 0, RUNTIME_CLASS(CAKAssmsListView),
		    size, pContext ) )
	{
		MessageBox( "Error setting up splitter CAKAssmsViewList view", "ERROR", MB_OK | MB_ICONERROR );
		return FALSE;
	}

	//change flag to show splitter created
  theApp.GetAKAssmsHub()->RegisterTarget ( this, -202 );
	m_bInitSplitter = true;

	//return TRUE instead of the parent method since that would
	//not show our window
	return TRUE;
}

BOOL CMDIChildExecute::PreCreateWindow(CREATESTRUCT& cs)
{
  cs.style |= WS_MAXIMIZE; //TODO:LJM added
	// TODO: Modify the Window class or styles here by modifying the CREATESTRUCT cs
	if( !CMDIChildWndEx::PreCreateWindow(cs) )
		return FALSE;

	return TRUE;
}

// CChildFrame diagnostics

#ifdef _DEBUG
void CMDIChildExecute::AssertValid() const
{
	CMDIChildWndEx::AssertValid();
}

void CMDIChildExecute::Dump(CDumpContext& dc) const
{
	CMDIChildWndEx::Dump(dc);
}
#endif //_DEBUG

///////////////////////////////////////////////////////////////////////
//  P2PeerMsg Handlers
//  NOTES: SQL server interaction handlers
//       : If there is a desire to optimise the message map
//         subjectively place frequent messages at the top and less
//         frequent messages at the bottom of the map
//
BEGIN_P2PeerMsg_MAP(CMDIChildExecute, P2PeerTarget)
    ON_P2PeerMsg_CATCH(MSG_SQLselect,On_SQLselectCatch)
    ON_P2PeerMsg(MSG_SQLselectItem,On_SQLselectItem)
END_P2PeerMsg_MAP()

//
//  MSG_Select message exception handler
//  NOTES: Query fails with displayed exception
//
//  Parameters:  P2PeerMsg *pMsg
//               Exception message
//
//  Returns:     msgRESULT
//               Completion summary
//
msgRESULT
CMDIChildExecute::On_SQLselectCatch ( P2PeerMsg *pMsg )
{
    // Because this is all problematic, we
    try
    {
      // Confirm thread context
      // NOTES: MSG_Select exceptions are processed sequentually
      //        in the context of the CWinApp thread
      //      : For this to all work CMainFrame must support
      //        WM_APP_P2PeerTarget message handler
      if ( !P2PeerContext(AfxGetApp()->m_nThreadID) )
        return P2PeerContextSwap ( theApp.GetMainWnd()->m_hWnd
                                 , WM_APP_P2PeerTarget );

      // Drop mapped handle
      // NOTES: Originating message is wrapped in exception
    }

    // Exceptions
    catch_pP2Pevent_Cancel
    catch_pCException_Cancel
    catch_ALL_Cancel

    // Tidy up and
    return msgHANDLED;
}

//
//  MSG_SQLselectItem selection handler
//  NOTES: Append to list view
//
//  Parameters:  P2PeerMsg *pMsg
//               Selected item message
//
//  Returns:     msgRESULT
//               Completion summary
//
msgRESULT
CMDIChildExecute::On_SQLselectItem  ( P2PeerMsg *pMsg )
{
    // Because this is all problematic, we
    try
    {
      // Confirm thread context
      // NOTES: MSG_SQLselectDatabaseItem refelctions are processed sequentually
      //        in the context of the CWinApp thread
      //      : For this to all work CMainFrame must support
      //        WM_APP_P2PeerTarget message handler
      if ( !P2PeerContext(AfxGetApp()->m_nThreadID) )
        return P2PeerContextSwap ( theApp.GetMainWnd()->m_hWnd
                                 , WM_APP_P2PeerTarget );
      CAKAssmsListView  *pListView = dynamic_cast<CAKAssmsListView*>(m_wndSplitter.GetPane(1,0));
      CListCtrl&         oListCtrl = pListView -> GetListCtrl();

      // Append selected items
      if ( pListView                    &&
           pMsg->r_datn().Exists("SQL")     )
      {
        P3PmsgNode oNodeSQL = pMsg->r_datn().SelectObject("SQL");
        if ( pListView->GetListCtrl().GetHeaderCtrl()->GetItemCount() <= 0 )
          CListCtrl_MakeColumns ( oListCtrl, oNodeSQL );
        CListCtrl_InsertRow ( oListCtrl, oNodeSQL );
      }

      // Environmental
      // NOTES: Broadcast connection available
      //      : Connection achieved, asynchronously terminate dialog
      return msgHANDLED;
    }


    // Exceptions
    catch_pP2Pevent_Cancel
    catch_pCException_Cancel
    catch_ALL_Cancel

    // Tidy up and
    return msgHANDLED;
}

///////////////////////////////////////////////////////////////////////////////
//  MFC CMDIChildExecute message handlers
BEGIN_MESSAGE_MAP ( CMDIChildExecute, CMDIChildWndEx )
    ON_WM_SIZE()
    ON_COMMAND(ID_QUERY_EXECUTE, &CMDIChildExecute::OnQueryExecute)
END_MESSAGE_MAP()

void
CMDIChildExecute::OnSize(UINT nType, int cx, int cy)
{
    // Delegate
    CMDIChildWndEx::OnSize(nType, cx, cy);
	
    CRect cr;
    GetWindowRect(&cr);

    if ( m_bInitSplitter         &&
         nType != SIZE_MINIMIZED     )
    {
      m_wndSplitter.SetRowInfo   ( 0, cr.Height()/2, 0 );
      m_wndSplitter.SetRowInfo   ( 1, cr.Height()/2, 0 );
      m_wndSplitter.SetColumnInfo( 0, cr.Width(), 50);
      //m_wndSplitter.SetColumnInfo( 1, cr.Width() / 2, 50);

      m_wndSplitter.RecalcLayout();
    }
}


void
CMDIChildExecute::OnQueryExecute()
{
    // TODO: Add your command handler code here
    CAKAssmsViewEditSQL *pEditView = dynamic_cast<CAKAssmsViewEditSQL*>(m_wndSplitter.GetPane(0,0));
    CAKAssmsListView    *pListView = dynamic_cast<CAKAssmsListView   *>(m_wndSplitter.GetPane(1,0));

    // Implementation
    //pEditView -> DumpContents  ( );
    //pListView -> ClearContents ( );
    CAKAssmsDoc *pAKAssmsDoc = dynamic_cast<CAKAssmsDoc *>(GetActiveDocument());

    // Build and execute query
    P2PeerMsgSP spMsgSQL = new P2PeerMsg ( GetP2PaddrHub(), _T("AKAssms")
                                         , MSG_SQLselect
                                         , (void *)0, 0 );
    CString strSQLstmt;
    pEditView -> GetEditCtrl().GetWindowText ( strSQLstmt );
    spMsgSQL -> r_datn().AddField ("SQLstmt"
                                  , DataBSTR16(strSQLstmt) );
    spMsgSQL -> r_datn().AddField ("MsgReply"
                                  , DataBSTR16(MSG_SQLselectItem) );
    AssignOwnership ( spMsgSQL );
    PostP2PeerMsg   ( spMsgSQL.Dereference() );

    // Preparation
    CListCtrl_DeleteAllColumns ( pListView->GetListCtrl() );
}
