// FTPDemoView.cpp : implementation of the CFTPDemoView class
//

#include "stdafx.h"
#include "FTPDemo.h"

#include "FTPDemoDoc.h"
#include "FTPDemoView.h"

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

/////////////////////////////////////////////////////////////////////////////
// CFTPDemoView

IMPLEMENT_DYNCREATE(CFTPDemoView, CFormView)

BEGIN_MESSAGE_MAP(CFTPDemoView, CFormView)
	//{{AFX_MSG_MAP(CFTPDemoView)
	ON_BN_CLICKED(IDC_CONNECT, OnConnect)
	ON_BN_CLICKED(IDC_GET, OnGet)
	ON_BN_CLICKED(IDC_SEND, OnSend)
	//}}AFX_MSG_MAP
	// Standard printing commands
	ON_COMMAND(ID_FILE_PRINT, CFormView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_DIRECT, CFormView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_PREVIEW, CFormView::OnFilePrintPreview)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFTPDemoView construction/destruction

CFTPDemoView::CFTPDemoView()
	: CFormView(CFTPDemoView::IDD)
{
	//{{AFX_DATA_INIT(CFTPDemoView)
	m_URL = _T("");
	m_Password = _T("");
	m_Login = _T("");
	//}}AFX_DATA_INIT
	// TODO: add construction code here
	m_FTPConnection = 0;
	m_Login = _T("anonymous");
	m_Password = _T("mail@mail.com");
}

CFTPDemoView::~CFTPDemoView()
{
	CloseConnection();
}

void CFTPDemoView::DoDataExchange(CDataExchange* pDX)
{
	CFormView::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFTPDemoView)
	DDX_Control(pDX, IDC_CLIENTLIST, m_ClientList);
	DDX_Control(pDX, IDC_SRVRLIST, m_SrvrList);
	DDX_Text(pDX, IDC_URL, m_URL);
	DDX_Text(pDX, IDC_PASSWORD, m_Password);
	DDX_Text(pDX, IDC_LOGIN, m_Login);
	//}}AFX_DATA_MAP
}

BOOL CFTPDemoView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return CFormView::PreCreateWindow(cs);
}

void CFTPDemoView::SetupList(CListCtrl &List)
{

	if( List.GetHeaderCtrl()->GetItemCount() == 0 )
	{
		RECT Rect;
		List.DeleteColumn(0);
		List.GetClientRect( &Rect );
		List.InsertColumn(0, "Name" );
		List.InsertColumn(1, "Size" );
		List.SetColumnWidth(0, Rect.right/4*3 );
		List.SetColumnWidth(1, Rect.right/4 );
	}
}

void CFTPDemoView::OnInitialUpdate()
{
	CFormView::OnInitialUpdate();
	GetParentFrame()->RecalcLayout();
	ResizeParentToFit();
	SetControls();
	
	SetupList( m_SrvrList );
	SetupList( m_ClientList );

}

/////////////////////////////////////////////////////////////////////////////
// CFTPDemoView printing

BOOL CFTPDemoView::OnPreparePrinting(CPrintInfo* pInfo)
{
	// default preparation
	return DoPreparePrinting(pInfo);
}

void CFTPDemoView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add extra initialization before printing
}

void CFTPDemoView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add cleanup after printing
}

void CFTPDemoView::OnPrint(CDC* pDC, CPrintInfo* /*pInfo*/)
{
	// TODO: add customized printing code here
}

/////////////////////////////////////////////////////////////////////////////
// CFTPDemoView diagnostics

#ifdef _DEBUG
void CFTPDemoView::AssertValid() const
{
	CFormView::AssertValid();
}

void CFTPDemoView::Dump(CDumpContext& dc) const
{
	CFormView::Dump(dc);
}

CFTPDemoDoc* CFTPDemoView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFTPDemoDoc)));
	return (CFTPDemoDoc*)m_pDocument;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CFTPDemoView message handlers

// Handler for the Connect button, to connect to FTP server
void CFTPDemoView::OnConnect() 
{
	UpdateData();

	// If not connected, then establish connection
	if( !m_FTPConnection )
	{
		if( MakeConnection() )
		{	// Connection established
			GetDlgItem( IDC_CONNECT )->SetWindowText( "Disconnect" );
			if( m_LocalDir.IsEmpty() )
			{
				char Buffer[_MAX_PATH];
				GetCurrentDirectory( sizeof(Buffer), Buffer );
				m_LocalDir = Buffer;
			}
			BuildClientFileList();
			BuildSrvrFileList();
		}
	}
	else // Otherwise if already connected, then disconnect
	{
		GetDlgItem( IDC_CONNECT )->SetWindowText( "Connect" );
		CloseConnection();
	}
	SetControls();
}

// Handler for the Send File ('>') button
void CFTPDemoView::OnSend() 
{
	// Determine which name in the local list is selected
	int i = m_ClientList.GetNextItem( -1, LVNI_SELECTED );
	if( i >= 0 )
	{
		CString LocalName;
		// Get name of selected file from local list
		LocalName = m_ClientList.GetItemText( i, 0 );
		
		// Invoke CFtpConnection::PutFile function to send the file
		if( m_FTPConnection->PutFile( LocalName, LocalName ) )
			BuildSrvrFileList(); // Refreash server file list
		else
			MessageBox( "Unable to send file (upload security?)" );
	}
	
}

// Handler for the Get File ('<') button
void CFTPDemoView::OnGet() 
{
	// Determine name of file selected in the Server list.
	int i = m_SrvrList.GetNextItem( -1, LVNI_SELECTED );
	if( i >= 0 )
	{
		CString Name;
		// Get name of selected file from server list
		Name = m_SrvrList.GetItemText( i, 0 );
		// Invoke the CFtpConnection::GetFile function to get the file
		m_FTPConnection->GetFile( Name, Name );
		// Refresh the local file list
		BuildClientFileList();
	}
}


// Start of Helper functions
// This function enables or disables controls as needed, depending 
// upon whether or not we are connected to the FTP server.
void CFTPDemoView::SetControls()
{
	CWnd* pWnd = GetDlgItem( IDC_SRVRLIST );
	pWnd->EnableWindow( m_FTPConnection!=0 );

	pWnd = GetDlgItem( IDC_CLIENTLIST );
	pWnd->EnableWindow( m_FTPConnection!=0 );
	pWnd = GetDlgItem( IDC_SEND );
	pWnd->EnableWindow( m_FTPConnection!=0 );
	pWnd = GetDlgItem( IDC_GET );
	pWnd->EnableWindow( m_FTPConnection!=0 );
	pWnd = GetDlgItem( IDC_URL );
	pWnd->EnableWindow( m_FTPConnection==0 );
}

void CFTPDemoView::BuildSrvrFileList()
{
	if( MakeConnection() )
	{
		CFtpFileFind Files( m_FTPConnection );
		BuildFileList( Files, m_SrvrList );
	}
	else
		MessageBox( "Unable to establish connection" );
}


void CFTPDemoView::BuildClientFileList()
{
	CFileFind Files;
	BuildFileList( Files, m_ClientList );
}

// BuildFileList
// This function gets a list of files names in a folder from either
// the local machine or the remote FTP server, and places the list into
// a List Control.
void CFTPDemoView::BuildFileList(CFileFind &Files, CListCtrl& List )
{
	int i, Count=0;
	BOOL bFound, NeedParent = TRUE;
	CString Str;

	// Remove any items already in the CListCtrl
	List.DeleteAllItems();

	// See if there are any files to place into the List Control
	bFound=Files.FindFile( );
	
	while( bFound ) // Loop through the files, if any
	{
		// Get information on the file
		bFound =  Files.FindNextFile();

		Str = Files.GetFileName();
		if( Str!= "." ) // Ignore the 'current folder' entry
		{
			// Add the filename to our List control
			i = List.InsertItem(Count++, Str, 0 );
			// Add either the text <DIR> or the file size, to our List Control
			if( Files.IsDirectory() )
			{
				if( Str==".." )
					NeedParent = FALSE;
				Str = "Dir";
			}
			else
				Str.Format( "%d", Files.GetLength() );
			List.SetItemText( i, 1, Str );
		}
	}
	if( NeedParent )
	{
		i = List.InsertItem(0, "..", 0 );
		List.SetItem( i, 1, LVIF_TEXT, "Dir", 0, 0, 0, 0 );
	}
}


// Establishes a connection to the FTP server
bool CFTPDemoView::MakeConnection()
{
	// Get current URL, Login and Password information into m_URL, m_Login, and m_Password
	UpdateData();

	// Close the connection if already open
	CloseConnection();

	try
	{
		// Establish the FTP connection
		m_FTPConnection = m_InternetSession.GetFtpConnection( m_URL, m_Login, m_Password );
	}
	catch(...)
	{	// Report Error
		if( !m_FTPConnection )
			MessageBox( "Error establishing FTP connection" );
		return( false );
	}
	return( true );
}

// Closes the connection to the FTP server
void CFTPDemoView::CloseConnection()
{
	if( m_FTPConnection ) // Make sure we have a connection to close
	{
		// Close and then delete the CFtpConnection object
		m_FTPConnection->Close();
		delete m_FTPConnection;
		m_FTPConnection = 0;
	}
}
