// DiagramEng.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "DiagramEng.h"

#include "MainFrm.h"
#include "ChildFrm.h"
#include "DiagramEngDoc.h"
#include "DiagramEngView.h"
#include "OutputBlockView.h"	// rqd. since COutputBlockView is used in InitInstance()
#include <afxadv.h>				// rqd. for CRecentFileList m_pRecentFileList, in OnFileRecentFileOpen()

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

/////////////////////////////////////////////////////////////////////////////
// CDiagramEngApp

BEGIN_MESSAGE_MAP(CDiagramEngApp, CWinApp)
	//{{AFX_MSG_MAP(CDiagramEngApp)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
	ON_COMMAND(ID_APP_EXIT, OnAppExit)
	ON_COMMAND(ID_FILE_OPEN, OnFileOpen)
	ON_COMMAND(ID_WND_CLOSE_ALL_DOCS, OnWndCloseAllDocs)
	//}}AFX_MSG_MAP
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
	// Standard print setup command
	ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
	// DiagramEng addition for OnFileRecentFileOpen() event handler fn
	ON_COMMAND_RANGE(ID_FILE_MRU_FILE1, ID_FILE_MRU_FILE16, OnFileRecentFileOpen)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDiagramEngApp construction

CDiagramEngApp::CDiagramEngApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CDiagramEngApp object

CDiagramEngApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CDiagramEngApp initialization

BOOL CDiagramEngApp::InitInstance()
{
	AfxEnableControlContainer();

	// 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

	// Change the registry key under which our settings are stored.
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization.
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));

	LoadStdProfileSettings();  // Load standard INI file options (including MRU)

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

	CMultiDocTemplate* pDocTemplate;
	pDocTemplate = new CMultiDocTemplate(
		IDR_DIAGRATYPE,
		RUNTIME_CLASS(CDiagramEngDoc),
		RUNTIME_CLASS(CChildFrame), // custom MDI child frame
		RUNTIME_CLASS(CDiagramEngView));
	AddDocTemplate(pDocTemplate);

	// DiagramEng (start)

	// -- OUTPUT BLOCK VIEW TEMPLATE
	m_pCOutputViewTemplate = new CMultiDocTemplate(
		IDR_OUTPUTVIEW,						// new menu resource
		RUNTIME_CLASS(CDiagramEngDoc),
		RUNTIME_CLASS(CChildFrame),			// custom MDI child frame
		// RUNTIME_CLASS(CDiagramEngView));	// old view type
		RUNTIME_CLASS(COutputBlockView));	// modifying the document template with the new view type (derived from CView)
		
	AddDocTemplate(m_pCOutputViewTemplate);

	// DiagramEng (end)

	// create main MDI Frame window
	CMainFrame* pMainFrame = new CMainFrame;
	if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
		return FALSE;
	m_pMainWnd = pMainFrame;

	// Enable drag/drop open
	m_pMainWnd->DragAcceptFiles();

	// Enable DDE Execute open
	EnableShellOpen();
	RegisterShellFileTypes(TRUE);

	// 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;

	// The main window has been initialized, so show and update it.
	pMainFrame->ShowWindow(m_nCmdShow);
	pMainFrame->UpdateWindow();

	return TRUE;
}


/////////////////////////////////////////////////////////////////////////////
// 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 CDiagramEngApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// CDiagramEngApp message handlers


CDocTemplate *CDiagramEngApp::GetCOutputViewTemplate() const
{
	return m_pCOutputViewTemplate;
}

void CDiagramEngApp::OnAppExit() 
{
	// TODO: Add your command handler code here

	// DiagramEng (start)
	int cancel = 0;					// flag indicating whether exit should be cancelled: (0) do not cancel, (1) cancel						
	CDiagramEngDoc *pDoc = NULL;	// pDoc used to call CDiagramEngDoc fns.
	
	// Save document contents
	cancel = SaveAllDocuments();
	if(cancel == 1)
	{
		return;
	}

	// Get the first document
	pDoc = GetDocumentGlobalFn();		// get a pointer-to-CDiagramEngDoc.

	// While there are still valid documents
	while(pDoc != NULL)						
	{
		if(pDoc != NULL)			// check that there is in fact a doc, i.e. the pDoc is not NULL
		{
			// The public OnFileCloseAccessor() is called since OnFileClose() is protected.
			cancel = pDoc->OnFileCloseAccessor();

			// If user cancels a file-save action in the OnFileClose() function then abort exit op.
			if(cancel == 1)
			{
				return;
			}
		}

		// Get the next document
		pDoc = GetDocumentGlobalFn();			// get a pointer-to-CDiagramEngDoc (the next doc).
	}

	CWinApp::OnAppExit();					// call the existing MFC-provided OnAppExit() in "Appui.cpp".
	// DiagramEng (end)
}

void CDiagramEngApp::OnFileOpen() 
{
	// TODO: Add your command handler code here

	// DiagramEng (start)

	// Create a new document onto which a diagram may be drawn/loaded
	OnFileNew();

	// Call the OnFileOpen() fn of the CDiagramEngDoc class, i.e. the Child Frame fn.
	CDiagramEngDoc *pDoc = GetDocumentGlobalFn();
	pDoc->OnFileOpenAccessor();

	// DiagramEng (end)
}

void CDiagramEngApp::OnWndCloseAllDocs() 
{
	// TODO: Add your command handler code here

	// DiagramEng (start)
	int cancel = 0;					// flag indicating whether exit should be cancelled: (0) do not cancel, (1) cancel						
	CDiagramEngDoc *pDoc = NULL;	// pDoc used to call CDiagramEngDoc fns.
	
	// Save document contents
	cancel = SaveAllDocuments();
	if(cancel == 1)
	{
		return;
	}

	// Get the first document
	pDoc = GetDocumentGlobalFn();	// get a pointer-to-CDiagramEngDoc.

	// While there are still valid documents
	while(pDoc != NULL)						
	{
		if(pDoc != NULL)			// check that there is in fact a doc, i.e. the pDoc is not NULL
		{
			// The public OnFileCloseAccessor() is called since OnFileClose() is protected.
			cancel = pDoc->OnFileCloseAccessor();

			// If user cancels a file-save action in the OnFileClose() function then abort exit op.
			if(cancel == 1)
			{
				return;
			}
		}

		// Get the next document
		pDoc = GetDocumentGlobalFn();		// get a pointer-to-CDiagramEngDoc (the next doc).
	}

	// DiagramEng (end)
}

void CDiagramEngApp::OnFileRecentFileOpen(UINT i)
{
	int btnSel;									// button selection
	int nIndex = i - ID_FILE_MRU_FILE1;			// index of recent file
	CString strFileName;						// file name and path
	CString sMsg;								// msg
	CDiagramEngDoc *pDoc = GetDocumentGlobalFn();	

	// ASSERTIONS
	ASSERT_VALID(this);
	ASSERT(m_pRecentFileList != NULL);
	ASSERT(i >= ID_FILE_MRU_FILE1);
	ASSERT(i < ID_FILE_MRU_FILE1 + (UINT)m_pRecentFileList->GetSize());
	ASSERT((*m_pRecentFileList)[nIndex].GetLength() != 0);

	// IF NO DOC, CREATE A DOC
	if(pDoc == NULL)
	{
		OnFileNew();
		pDoc = GetDocumentGlobalFn();
	}

	// CHECK pDoc
	if(pDoc == NULL)
	{
		return;
	}

	// CHECK FOR THE EXISTENCE OF A MODEL ON THE DOC: GET THE SYSTEM MODEL BY REFERENCE!
	CSystemModel &system_model = pDoc->GetSystemModel();
	if((system_model.GetBlockList().size() != 0) || (system_model.GetConnectionList().size() != 0) || (system_model.GetAnnotationList().size() != 0))
	{
		sMsg.Format(" A system model already exists.    \n Do you want to erase it? \n");
		btnSel = AfxMessageBox(sMsg, MB_YESNOCANCEL, 0);

		if(btnSel == IDYES)
		{
			// Delete System Model Lists
			system_model.DeleteBlockList();
			system_model.DeleteConnectionList();
			system_model.DeleteSourceOutputLoopLists();
			system_model.DeleteAnnotationList();

			// Set flags and redraw the doc
			pDoc->SetModifiedFlag(TRUE); 	// set the doc. as having been modified to prompt user to save
			pDoc->UpdateAllViews(NULL); 	// indicate that sys. should redraw.
		}
		else if(btnSel == IDNO)				// Create a new document for the model
		{
			OnFileNew();					// Create a new document
			pDoc = GetDocumentGlobalFn();	// Get a ptr to the new document in preparation for reading data from file
			if(pDoc == NULL)
			{
				return;
			}
		}
		else if(btnSel == IDCANCEL)
		{
			return;
		}
	}

	// GET THE FILE NAME/PATH
	strFileName = (LPCTSTR)(*m_pRecentFileList)[nIndex];
	pDoc->SetFilePath(strFileName);
	pDoc->SetTitle(strFileName);
	
	// IF UNABLE TO READ DATA FROM FILE, THEN REMOVE THE RECENT FILE LIST ENTRY: (0) NO ERROR, (1) ERROR
	if(pDoc->ReadDiagramEngDataFromFile(strFileName) == 1)
	{
		m_pRecentFileList->Remove(nIndex);
	}

	// MSGs
	//strMsg.Format(" CDiagramEngApp::OnFileRecentFileOpen()\n Open file (%d) '%s'.\n", ((nIndex) + 1), strFileName);
 	//AfxMessageBox(strMsg);
}

int CDiagramEngApp::SaveAllDocuments()
{
	int btnSel = -1;
	int cancel = 0;
	CString sMsg;
	CString sPathName;

	// Get the first doc template in the app
	POSITION pos = GetFirstDocTemplatePosition();

	// Iterate through all docs
	while(pos)
	{
		// Get the first CDocTemplate obj.
		CDocTemplate *pTemplate = GetNextDocTemplate(pos);

		// Get the string describing the doc
		CString sDocName;
		pTemplate->GetDocString(sDocName, CDocTemplate::docName);

		// If the doc is a DiagramEng "DiaEng" doc
		if(sDocName == _T("DiaEng"))
		{
			// Get the posn of the first doc in the list of docs associated with this template
			POSITION posDoc = pTemplate->GetFirstDocPosition();

			// While there is a first doc or a subsequent doc
			// If there is a first doc, then posDoc is not NULL: o/wise if there is no next doc, then posDoc = NULL.
			while(posDoc)
			{
				// Get a pointer to the doc
				CDiagramEngDoc* pDoc = (CDiagramEngDoc*)pTemplate->GetNextDoc(posDoc);
			
				if(pDoc != NULL)	
				{
					// Check whether document has been modified: non-zero => modified, zero => not modified
					if(pDoc->IsModified())	
					{
						// Make the view active and flash it
						POSITION pos_view = pDoc->GetFirstViewPosition();
						if(pos_view != NULL)
						{
							CDiagramEngView* pFirstView = (CDiagramEngView*)pDoc->GetNextView(pos_view); // first view
							CFrameWnd *pFrameWnd = pFirstView->GetParentFrame();	// get parent frame
							pFrameWnd->BringWindowToTop();							// bring window to top
							pFrameWnd->FlashWindow(TRUE);							// flash window once			
						}

						// Get path/file name
						sPathName = pDoc->GetFilePath();
						if(sPathName != "")
						{
							sMsg.Format("\n Do you want to save changes to the document:\n %s?    \n", sPathName);
						}
						else
						{
							sMsg.Format("\n Do you want to save changes to the document?    \n");
						}

						// Display msg. box and process btn selection
						btnSel = AfxMessageBox(sMsg, MB_YESNOCANCEL, 0);

						if(btnSel == IDYES)					// save changes
						{
							pDoc->OnFileSaveAccessor();		// chain to OnFileSave()
						}
						else if(btnSel == IDNO)				// do not save changes
						{
							pDoc->SetModifiedFlag(FALSE);	// set as unmodified
						}
						else if(btnSel == IDCANCEL)			// do not save changes
						{
							cancel = 1;						
							return cancel;
						}
					}	
				}
			}// end while(posDoc)

		}// end if(sDocName)

	}// end while(pos)

	return cancel;
}
