// PNPOP3.cpp: implementation of the CPOP3 class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "PNPOP3.h"

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

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CPNPOP3::CPNPOP3()
{

}

CPNPOP3::~CPNPOP3()
{

}

bool CPNPOP3::Login(const char *User, const char *Password)
{
	if( SendCommand( "USER %s\n", User, 0, "+" ) == FALSE )
		return( false );
	if( SendCommand( "PASS %s\n", Password, 0, "+" ) == FALSE )
		return( false );
	return( true );

}

BOOL CPNPOP3::Connect( LPCTSTR lpszHostAddress, UINT nHostPort )
{
	if( CPNCommandSocket::Connect( lpszHostAddress, nHostPort ) )
	{
		if( !SendCommand( 0, 0, 0, "+" ) )
			return( FALSE );
		else
			return( TRUE );
	}
	return FALSE;
}

int CPNPOP3::GetMsgCount()
{
	char Msg[128];
	int Off=0;
	m_Count=0;
	CString Count;

	if( SendCommand( "LIST\n", 0, &Count, "+" ) )
	{
		if( atoi( ((LPCSTR)Count)+4 ) == 0 )
			return(0);
		do {
			if( ReceiveLine( Msg, sizeof(Msg)) <=0 )
				return( -1 );
			if( Msg[0] != '.' )
			{
				m_MessageIDs[ m_Count ] = atoi( Msg );
				while( Msg[Off] && Msg[Off] >' ' )
					Off++;
				m_MessageSize[m_Count ] = atoi( Msg+Off );
			}
			m_Count++;
		} while( Msg[0] != '.' );
	}
	return( m_Count?m_Count-1:0 );
}

bool CPNPOP3::GetMsg(int Index, CString& Dest)
{
	Dest.Empty();

	CString strIndex;
	strIndex.Format( "%d", m_MessageIDs[Index] );

	SendCommand( "RETR %s\n", strIndex, 0, "+");
	char* pBuffer = Dest.GetBuffer( m_MessageSize[ Index ]+1 );
	int Count = Receive( pBuffer, m_MessageSize[Index], 0 );
	if( Count>=0 )
		pBuffer[m_MessageSize[Index]] = '\0';
	Dest.ReleaseBuffer();

	return( Count>=0?true:false );
}

bool CPNPOP3::ParseMsg( CString& Msg, CString& From, CString& Subj, CString& Date )
{

	int i;
	From.Empty();
	Subj.Empty();
	Date.Empty();

	int Pos = Msg.Find( "From: ", 0 );
	if( Pos >= 0 )
	{
		i=Pos+6;
		while( Msg[i] && Msg[i]!='\r' )
			From += Msg[i++];
	}

	Pos = Msg.Find( "Date: ", 0 );
	if( Pos >= 0 )
	{
		i = Pos+6;
		while( Msg[i] && Msg[i]!='\r' )
			Date += Msg[i++];
	}

	Pos = Msg.Find( "Subject: ", 0 );
	if( Pos >= 0 )
	{
		i = Pos+8;
		while( Msg[i] && Msg[i]!='\r' )
			Subj += Msg[i++];
	}

	Pos = Msg.Find( "Status: ", 0 );
	if( Pos >= 0 )
	{
		Msg.Delete( 0, Pos+7 );
		while( Msg[0] && Msg[0]!='\r' )
			Msg.Delete( 0, 1 );
		if( !Msg.IsEmpty() )
			Msg.Delete( 0, 1 );
	}

	Msg.TrimLeft();
	Msg.TrimRight();
	Msg+="\n";
	return( true );
}
