// Connect2ServerDlg.cpp : implementation file
//

#include "stdafx.h"
#define   SECURITY_WIN32
#include "security.h"
#include "AKAssms.h"
#include "Connect2ServerDlg.h"
#include "afxdialogex.h"
#include "P2Pwin32.h"
#include "CDialog_Ext.h"
#include "CWnd_Ext.h"
#include "CComboBox_Ext.h"
#include "WSA_Ext.h"

#define AUTH_WINDOWS   1
#define AUTH_SQLSERVER 2

// CConnect2ServerDlg dialog

IMPLEMENT_DYNAMIC(CConnect2ServerDlg, CDialogEx)

CConnect2ServerDlg::CConnect2ServerDlg ( CWnd* pParent /*=NULL*/)
	                : CDialogEx(CConnect2ServerDlg::IDD, pParent)
{
    m_strServername  = _T("IWSQLServer10");
    TCHAR szUsername[UNLEN+1];
    DWORD szUsernameSize = sizeof(szUsername)/sizeof(szUsername[0]);
    GetUserNameEx ( NameSamCompatible, szUsername, &szUsernameSize );
    m_strUsername    = szUsername;
    m_strPassword    = _T("");
}

CConnect2ServerDlg::~CConnect2ServerDlg()
{
}

///////////////////////////////////////////////////////////////////////////////
//  Operations

void
CConnect2ServerDlg::ManageControlStatus()
{
    // TODO: Add your control notification handler code here
    UpdateData ( TRUE );
    BOOL bEoD = TRUE;
    if ( CComboBox_GetCurSelData(m_cboAuthentication) == AUTH_WINDOWS )
      bEoD = FALSE;
    m_cboUsername.EnableWindow ( bEoD );
    m_edtPassword.EnableWindow ( bEoD );
}

///////////////////////////////////////////////////////////////////////////////
//  MFC Virtual overrides

void
CConnect2ServerDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_CBO_Authentication, m_cboAuthentication);
    DDX_Control(pDX, IDC_CBO_ServerName, m_cboServername);
    DDX_Control(pDX, IDC_CBO_ServerType, m_cboServerType);
    DDX_Control(pDX, IDC_CBO_Username, m_cboUsername);
    DDX_Control(pDX, IDC_EDT_Password, m_edtPassword);
    DDX_CBString(pDX, IDC_CBO_ServerName, m_strServername);
    DDV_MaxChars(pDX, m_strServername, 1024);
    DDX_CBString(pDX, IDC_CBO_Username, m_strUsername);
    DDV_MaxChars(pDX, m_strUsername, 255);
    DDX_Text(pDX, IDC_EDT_Password, m_strPassword);
    DDV_MaxChars(pDX, m_strPassword, 255);
}

BOOL
CConnect2ServerDlg::OnInitDialog()
{
    // Compliments wizard
  __super::OnInitDialog();
    P2PmsgMgr *pP2PappConfig = theApp.GetP2Pconfig();
    P3PmsgNode oNodeDialogs  = pP2PappConfig -> DeclareNode ( _T("Dialogs"), 0 ).r_Object();
               m_oNodeThis   = oNodeDialogs.DeclareNode ( _T("CConnect2ServerDlg"), 0 ).r_Object();

    // Server Type Combo
    CComboBox_InsertStringData ( m_cboServerType
                               , _T("Database Engine"), 1 );
    m_cboServerType.SetCurSel ( 0 );

    // Server Name Combo
    P3PmsgNode oNodeServerName = m_oNodeThis.DeclareNode ( _T("ServerName"), 0 ).r_Object();
    CComboBox_Deserialise ( m_cboServername, oNodeServerName );
    if ( m_cboServername.GetCount() <= 0 )
    {
      CString strServerName;
              strServerName  = WSA_GetHostName();
              strServerName += _T("\\SQLEXPRESS");
      CComboBox_InsertStringData ( m_cboServername, strServerName, 0 );
    }

    // Authentication Combo
    CComboBox_InsertStringData ( m_cboAuthentication
                               , _T("Windows Authentication"), AUTH_WINDOWS );
    CComboBox_InsertStringData ( m_cboAuthentication
                               , _T("SQL Server Authentication"), AUTH_SQLSERVER );
    m_cboAuthentication.SetCurSel ( 0 );

    // Username Combo
    P3PmsgNode oNodeUsername = m_oNodeThis.DeclareNode ( _T("Username"), 0 ).r_Object();
    CComboBox_Deserialise ( m_cboUsername, oNodeUsername );

    //EnumAvailableSqlServers();getdatasources();
    ManageControlStatus ( );
    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}

///////////////////////////////////////////////////////////////////////////////
//  MFC CConnect2ServerDlg message handlers
BEGIN_MESSAGE_MAP(CConnect2ServerDlg, CDialogEx)
    ON_BN_CLICKED(IDCANCEL, &CConnect2ServerDlg::OnBnClickedCancel)
    ON_BN_CLICKED(IDC_BTN_CONNECT2SERVER, &CConnect2ServerDlg::OnClickedBtnConnect2Server)
    ON_COMMAND(IDOK, &CConnect2ServerDlg::OnOK)
    ON_CBN_SELCHANGE(IDC_CBO_Authentication, &CConnect2ServerDlg::OnSelchangeCboAuthentication)
END_MESSAGE_MAP()

void
CConnect2ServerDlg::OnBnClickedCancel()
{
    // TODO: Add your control notification handler code here
}

void
CConnect2ServerDlg::OnClickedBtnConnect2Server()
{
    extern P2Paddr g_oP2PaddrODBCserver;
    // TODO: Add your control notification handler code here
    try
    {
      P2PeerMsgSP spMsgSQL;
      UpdateData ( TRUE );
      // Build SQLConnect request
      if ( 0 )
      {
        P2Paddr oAddr1 = GetP2PaddrHub();
        P2Paddr oAddr2 = GetP2PaddrHub();
        spMsgSQL = new P2PeerMsg ( GetP2PaddrHub(), g_oP2PaddrODBCserver
                                 , _T("SQLConnect")
                                 , (void *)0, 0 );
        spMsgSQL -> r_datn().AddField ("ServerName", DataBSTR08(m_strServername) );
        spMsgSQL -> r_datn().AddField ("Username",   DataBSTR08(m_strUsername) );
        spMsgSQL -> r_datn().AddField ("Password",   DataBSTR08(m_strPassword) );
      }

      // Build SQLDriverConnect request
      if ( 2 )
      {
        P2Paddr oAddr1 = GetP2PaddrHub();
        P2Paddr oAddr2 = GetP2PaddrHub();
        spMsgSQL = new P2PeerMsg ( GetP2PaddrHub(), g_oP2PaddrODBCserver
                                 , _T("SQLDriverConnect")
                                 , (void *)0, 0 );
        CString strConnection;
        strConnection += _T("DRIVER={SQL Server};");
        strConnection += CString("SERVER=") += m_strServername += CString(";");
        CString strAuthentication;
        if ( CComboBox_GetCurSelData(m_cboAuthentication) == AUTH_WINDOWS )
          strAuthentication = _T("Trusted_Connection=yes;");
        if ( CComboBox_GetCurSelData(m_cboAuthentication) == AUTH_SQLSERVER )
          strAuthentication.Format ( _T("UID=%s;PWD=%s;"), m_strUsername, m_strPassword );
        strConnection += strAuthentication;
        spMsgSQL -> r_datn().AddField ("ConnectionString", DataBSTR08(strConnection) );
      }

ASSERT(GetHubID()>0);
ASSERT(!spMsgSQL->IsReflected());
spMsgSQL->Print (stdout);

      // Implementation
      AssignOwnership ( spMsgSQL );
      PostP2PeerMsg ( spMsgSQL.Dereference() );
      CDialog_DisableAllControls ( this );
    }

    // Exceptions
    catch_pP2Pevent_Cancel
    catch_pCException_Cancel
    catch_ALL_Cancel
}


///////////////////////////////////////////////////////////////////////
//  P2PeerMsg Handlers
//  NOTES: SQL connection management implementation 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(CConnect2ServerDlg, P2PeerTarget)
    ON_P2PeerMsg_CATCH(T_SQLConnect,On_SQLconnect2serverCatch)
    ON_P2PeerMsg_REFLECT(T_SQLConnect,On_SQLconnect2serverReflect)
    ON_P2PeerMsg_CATCH(T_SQLDriverConnect,On_SQLconnect2serverCatch)
    ON_P2PeerMsg_REFLECT(T_SQLDriverConnect,On_SQLconnect2serverReflect)
END_P2PeerMsg_MAP()

//
//  MSG_ContentRange message exception handler
//  NOTES: Removal of "Content-Range" handle effectively cancels
//         sequence and recovers resources
//
//  Parameters:  P2PeerMsg *pMsg
//               Exception message
//
//  Returns:     msgRESULT
//               Completion summary
//
msgRESULT
CConnect2ServerDlg::On_SQLconnect2serverCatch ( P2PeerMsg *pMsg )
{
    // Because this is all problematic, we
    try
    {
      // Confirm thread context
      // NOTES: MSG_Connect2server 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 ( AfxGetMainWnd()->m_hWnd
                                 , WM_APP_P2PeerTarget );

      // Drop mapped handle
      // NOTES: Originating message is wrapped in exception
      //RemoveRCFileHandle ( (*pMsg)[1].GetSource() );
    }

    // Exceptions
    catch_pP2Pevent_Cancel
    catch_pCException_Cancel
    catch_ALL_Cancel

    // Tidy up and
    CDialog_EnableAllControls ( this );
    return msgHANDLED;
}

//
//  MSG_ContentInChunks reflection handler
//  NOTES: Reflection is performed by P2PeerioAKA object upon
//         transmission of previous content chunk.
//       : Facilitates the break up of large download files into
//         multiple chunks and provides for load balancing
//
//  Parameters:  P2PeerMsg *pMsg
//               Reflection message
//
//  Returns:     msgRESULT
//               Completion summary
//
msgRESULT
CConnect2ServerDlg::On_SQLconnect2serverReflect  ( P2PeerMsg *pMsg )
{
    // Because this is all problematic, we
    try
    {
      // Confirm thread context
      // NOTES: MSG_Connect2server 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 );
ASSERT(AfxCheckMemory());


      // Environmental
      // NOTES: Broadcast connection available
      //      : Connection achieved, asynchronously terminate dialog
      CDialog_EnableAllControls ( this );
      PostMessage ( WM_COMMAND, IDOK, 0 );
      return msgHANDLED;
    }

    // Exceptions
    catch_pP2Pevent_Cancel
    catch_pCException_Cancel
    catch_ALL_Cancel

    // Tidy up and
    CDialog_EnableAllControls ( this );
    return msgHANDLED;
}


void
CConnect2ServerDlg::OnOK()
{
    // Server Name Combo
    P3PmsgNode oNodeServername = m_oNodeThis.SelectObject( _T("ServerName") );
    CComboBox_Serialise ( m_cboServername, oNodeServername );

    // Username Combo
    P3PmsgNode oNodeUsername = m_oNodeThis.SelectObject ( _T("Username") );
    CComboBox_Serialise ( m_cboUsername, oNodeUsername );

    // SQL-Explorer root label
    theApp.GetP2PmsgMgr()->r_Attr().DeclareField ( _T("!Servername"), P3PmsgData(m_strServername) );
    theApp.GetP2PmsgMgr()->r_Attr().DeclareField ( _T("!Username"),   P3PmsgData(m_strUsername) );

    // Delegate
m_oNodeThis.Print(stdout,1);
    CWnd_BCastMessage ( WM_APP_CONNECT_SQLSERVER, 0, 0 );
  __super::OnOK ( );
}


void
CConnect2ServerDlg::OnSelchangeCboAuthentication()
{
    // TODO: Add your control notification handler code here
    ManageControlStatus ( );
}
