/*
*********************************************************************
*
*	The Essence of OLE
*
*	Source code sample
*
*	Copyright (c) 1996, Rolling Thunder Computing, Ipswich MA
*
*	e-mail: essence@rollthunder.com
*	CompuServe: 73540,3430
*	Web: http://www.rollthunder.com
*
*********************************************************************
*/

// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "script.h"
#include "scriptsite.h"
#include "scriptdoc.h"
#include "scriptview.h"
#include "control1view.h"
#include "controllistdlg.h"
#include "MainFrm.h"
#include "ctrlholder.h"

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

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

#define WM_INITFINISHED		WM_USER + 0x100
#define NENGINEMAX	10

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	//{{AFX_MSG_MAP(CMainFrame)
	ON_WM_CREATE()
	ON_WM_CLOSE()
	ON_COMMAND(ID_CONTROL_REPLACEEXISTING, OnControlReplaceexisting)
	ON_WM_INITMENUPOPUP()
	//}}AFX_MSG_MAP
	ON_COMMAND_RANGE (ID_ENGINE_BASE, ID_ENGINE_BASE + NENGINEMAX, OnEngineCommand) 
	ON_UPDATE_COMMAND_UI_RANGE (ID_ENGINE_BASE, ID_ENGINE_BASE + NENGINEMAX, OnUpdateEngineCommand) 
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

CLSID	g_EngineClsid ;
CCtrlHolder*	g_pControl1 = NULL ;

int		g_EngineCount = 0 ;
char	g_EngineName [NENGINEMAX][256] ;
CLSID	g_EngineClsidList [NENGINEMAX] ;

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
//	m_EngineChoice = ID_ENGINE_BASE ;	
}

CMainFrame::~CMainFrame()
{
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	if (!m_wndToolBar.Create(this) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}

	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		  sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}

	// TODO: Remove this if you don't want tool tips or a resizeable toolbar
	m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() |
		CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);

	// TODO: Delete these three lines if you don't want the toolbar to
	//  be dockable
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);

/*
Find previously selected class of control and create it now. 
*/
	CString CntrlClsidString = AfxGetApp( )->GetProfileString ("Control", "clsid", 
		"{A8C3B720-0B5A-101B-B22E-00AA0037B2FC}") ;
	
	CreateMyControl (CntrlClsidString) ;
/*
Make list of installed script engines.
Iterate through the registry to find all the script engines.
*/

	HKEY hKey, hClsidKey, hScriptKey ;
	DWORD index = 0;
	char ClsidString [128] ;

	RegOpenKey (HKEY_CLASSES_ROOT, "Clsid", &hKey) ;

/*
For each registered class ID in that section, open the class ID and look
for the presence of the key "Control".
*/
	while (RegEnumKey (hKey, index, ClsidString, sizeof (ClsidString)) == ERROR_SUCCESS)
	{
		RegOpenKey (hKey, ClsidString, &hClsidKey) ;

		if (RegOpenKey (hClsidKey, "OLEScript", &hScriptKey) == ERROR_SUCCESS)
		{
/*
Control key found, read name and add it to menu.
put name and class ID into list box.
*/
			long namelength = 256 ;
			RegQueryValue (hKey, ClsidString, &g_EngineName [g_EngineCount][0], &namelength) ;

			USES_CONVERSION
			CLSIDFromString (A2W(ClsidString), &g_EngineClsidList[g_EngineCount]) ;

			RegCloseKey (hScriptKey) ;
			g_EngineCount ++ ;
			
			if (g_EngineCount == NENGINEMAX)
			{
				break ;
			}
		}

		RegCloseKey (hClsidKey) ;
		index ++ ;
	}  

	if (g_EngineCount == 0)
	{
		AfxMessageBox ("Couldn't find any script engines, app terminating.") ;
	}

/*
Post message selecting script engine.
*/
	PostMessage (WM_COMMAND, ID_ENGINE_BASE, 0) ;

	return 0;
}

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

	return CFrameWnd::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers

BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) 
{
	RECT r ;
	GetClientRect (&r) ;

	m_SplitterWnd.CreateStatic (this, 1, 2) ;
	m_SplitterWnd.CreateView (0, 0, RUNTIME_CLASS(CScriptView), CSize (r.right - 150,100), pContext) ;	
	m_SplitterWnd.CreateView (0, 1, RUNTIME_CLASS(CControl1View), CSize (150,100), pContext) ;	

	return TRUE ;
}

void CMainFrame::OnClose() 
{
	if (g_pControl1)
	{
		AfxGetApp( )->WriteProfileString ("Control", "clsid", 
			(LPCTSTR)(g_pControl1->m_ClsidString)) ;
	}
	CFrameWnd::OnClose();
}

void CMainFrame::OnControlReplaceexisting() 
{
	CControlListDlg dlg ;
	
	if (dlg.DoModal( ) == IDOK)
	{
		CreateMyControl (dlg.m_ClsidString) ;
	}
}


void CMainFrame::CreateMyControl (CString ClsidString)
{
	CRect r (0, 0, 150, 150) ;

	if (g_pControl1)
	{
		g_pControl1->DestroyWindow( ) ;
		delete g_pControl1 ;
	}

	g_pControl1 = new CCtrlHolder (ClsidString) ;
	
	if (!g_pControl1->CreateControl ((LPCTSTR)g_pControl1->m_ClsidString, "", WS_CHILD | WS_VISIBLE, r, 
		m_SplitterWnd.GetPane (0, 1), 1))
	{
		AfxMessageBox ("Unable to create specified control. Use the menu"
			"item 'Control - Replace Existing' to add a different one") ;
		delete g_pControl1 ;
		g_pControl1 = NULL ;
	}
}


void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu) 
{
	static BOOL bInit = FALSE ;

/*
If this is the first time, add all the script engine names to the menu.
*/
	
	if (nIndex == 2 && bInit == FALSE)
	{
		pPopupMenu->RemoveMenu (ID_ENGINE_DUMMY, MF_BYCOMMAND) ;

		for (int i = 0 ; i < g_EngineCount ; i ++) 
		{
			pPopupMenu->AppendMenu (MF_STRING, ID_ENGINE_BASE + i, &g_EngineName [i][0] ) ;
		}

		bInit = TRUE ;
	}

	CFrameWnd::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
}

void CMainFrame::OnEngineCommand (UINT id)
{
	g_EngineClsid = g_EngineClsidList [id - ID_ENGINE_BASE] ;
	m_EngineChoice = id ;
}

void CMainFrame::OnUpdateEngineCommand(CCmdUI* pCmdUI) 
{	
	pCmdUI->SetRadio (m_EngineChoice == pCmdUI->m_nID)	;
}