// HttpSvr.cpp : Defines the class behaviors for the application.
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) 1996 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
//
// Note that your filters probably won't have an #ifdef like this one.
// The project file for this sample allows you to build the sample as
// a statically linked regular MFC DLL (that is, with _AFXDLL defined)
// or as a DLL that doesn't use MFC classes aside from the ISAPI 
// support classes (that is, without _AFXDLL defined).

#include "stdafx.h"

#include "Listen.h"
#include "HttpSvr.h"
#include "Http.h"
#include "MainFrm.h"
#include "HttpDoc.h"
#include "HttpView.h"
#include "ReqSock.h"
#include "RootPage.h"
#include "GenPage.h"
#include "NamePage.h"

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

/////////////////////////////////////////////////////////////////////////////
// CHttpSvrApp

BEGIN_MESSAGE_MAP(CHttpSvrApp, CWinApp)
	//{{AFX_MSG_MAP(CHttpSvrApp)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
	ON_COMMAND(IDM_SVR_OPTIONS, OnSvrOptions)
	//}}AFX_MSG_MAP
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CHttpSvrApp construction

CHttpSvrApp::CHttpSvrApp()
{
}

CHttpSvrApp::~CHttpSvrApp()
{
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CHttpSvrApp object

CHttpSvrApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CHttpSvrApp initialization

BOOL CHttpSvrApp::InitInstance()
{
	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif
	SetRegistryKey( IDS_REGISTRY_KEY ); // use the registry
	LoadStdProfileSettings(0);  // Load standard INI file options (including MRU)

	// try to get the default host name....
	int nOk =  gethostname( m_strDefSvr.GetBuffer(255), 255 );
	m_strDefSvr.ReleaseBuffer();
	if ( nOk != 0 )
	{
		// get the computer server name....
		DWORD dwLen = MAX_COMPUTERNAME_LENGTH+1;
		GetComputerName( m_strDefSvr.GetBuffer( dwLen ), &dwLen );
		m_strDefSvr.ReleaseBuffer();
		// all lower-case....
		m_strDefSvr.MakeLower();
	}

	// see if we get the default or specify a server name....
	m_nSvrName = GetProfileInt( "ServerName", "SpecifyName", 0 );
	if ( m_nSvrName != 0 )
		m_strServer = GetProfileString( "ServerName", "Name", "" );
	else
		m_strServer = m_strDefSvr;

	// get the root directory from the registry....
	GetRootDir();

	// kick-off the server stuff....
	if ( !AfxSocketInit() || !StartListen() )
	{
		AfxMessageBox(IDS_LISTEN_FAILED, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}		
	m_timeStarted = CTime::GetCurrentTime();

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views.

	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CHttpSvrDoc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CHttpSvrView));
	AddDocTemplate(pDocTemplate);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Dispatch commands specified on the command line
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

#ifdef _MAC
	// Enable drag/drop open.  We don't call this in Win32, since a
	//  document file extension wasn't chosen while running AppWizard.
	m_pMainWnd->DragAcceptFiles();
#endif

	// check for SvrAdmin subfolder of the root....
	m_bListIcon = (BOOL)GetProfileInt( "Settings", "ListingIcons", 1 );
	CString strAdmin = m_strRoot + SEPCHAR + "SvrAdmin";
	DWORD dwAttr = GetFileAttributes( strAdmin );
	if ( dwAttr == (DWORD)(-1) || (dwAttr & FILE_ATTRIBUTE_DIRECTORY) == 0 )
		m_bListIcon = FALSE; // don't allow icons

	return TRUE;
}

int CHttpSvrApp::ExitInstance() 
{
	// save settings to registry....
	WriteProfileString( "Directories", "WebPagesRoot", m_strRoot );
	WriteProfileInt( "Settings", "ListingIcons", m_bListIcon );
	WriteProfileInt( "ServerName", "SpecifyName", m_nSvrName );
	if ( m_nSvrName ) // save it....
		WriteProfileString( "ServerName", "Name", m_strServer );
	else // delete it....
		WriteProfileString( "ServerName", "Name", NULL );
	
	return CWinApp::ExitInstance();
}

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
		// No message handlers
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

// App command to run the dialog
void CHttpSvrApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// CHttpSvrApp commands

void CHttpSvrApp::OnSvrOptions() 
{
	// add and initialize the general page....
	CPropertySheet propOptions( IDS_OPTIONS );
	CGenPage genPage;
	genPage.m_bListIcon = m_bListIcon;
	propOptions.AddPage( &genPage );

	// add and initialize the root dir page....
	CRootPage rootPage;
	rootPage.m_strRoot = m_strRoot;
	propOptions.AddPage( &rootPage );

	// add and initialize the name page....
	CNamePage namePage;
	namePage.m_nNameSetting = m_nSvrName;
	if ( m_nSvrName )
		namePage.m_strName = m_strServer;
	propOptions.AddPage( &namePage );

	propOptions.DoModal();
}

void CHttpSvrApp::GetRootDir( const CString* pstrNewRoot )
{
	CString strRoot = GetProfileString( "Directories", "WebPagesRoot" );
	if ( strRoot.IsEmpty() )
	{
		strRoot.LoadString( IDS_DEF_ROOT );
		strRoot = CString(SEPCHAR) + strRoot;
	}
	// ensure no final separator character....
	if ( strRoot[strRoot.GetLength()-1] == SEPCHAR )
		strRoot = strRoot.Left( strRoot.GetLength()-1 );
	// make into a full path string....
	GetFullPathName( strRoot, MAX_PATH, 
		m_strRoot.GetBuffer(MAX_PATH), NULL);
	m_strRoot.ReleaseBuffer();
}

BOOL CHttpSvrApp::StartListen( void )
{
	BOOL bOk = FALSE;
	if ( m_listen.Create( PORT_HTTP, SOCK_STREAM, FD_ACCEPT ) )
	{
		bOk = m_listen.Listen();
	}

	return bOk;
}


BOOL CHttpSvrApp::OnIdle(LONG lCount) 
{
	BOOL bMore = CWinApp::OnIdle(lCount);
	// if we still need more processing time, ask for it...
	CHttpSvrDoc* pDoc = (CHttpSvrDoc*)(((CFrameWnd*)m_pMainWnd)->GetActiveDocument());
	if ( pDoc->IdleProc( lCount ) )
		bMore = TRUE;
	return bMore;
}

void AddFile( CString& strPath, UINT uStr )
{
	CString strFile;
	strFile.LoadString( uStr );
	AddFile( strPath, strFile );
}

void AddFile( CString& strPath, const CString& strFile )
{
	if ( strPath.GetAt( strPath.GetLength()-1 ) != SEPCHAR )
		strPath += SEPCHAR;
	strPath += strFile;
}


CDocument* CHttpSvrApp::GetTopDocument( void )
{
	CDocument* pDoc = NULL;
	POSITION pos = GetFirstDocTemplatePosition();
	if ( pos )
	{
		CDocTemplate* pTemplate = GetNextDocTemplate( pos );
		if ( pTemplate )
		{
			pos = pTemplate->GetFirstDocPosition();
			pDoc = pTemplate->GetNextDoc( pos );
		}
	}
	return pDoc;
}
