/* Anakrino - .NET Reflection Browser
 * Copyright (C) 2001-2002  Jay Freeman (saurik)
*/

/*
 *        Redistribution and use in source and binary
 * forms, with or without modification, are permitted
 * provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the
 *    above copyright notice, this list of conditions
 *    and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions
 *    and the following disclaimer in the documentation
 *    and/or other materials provided with the
 *    distribution.
 * 3. The name of the author may not be used to endorse
 *    or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef ANAKRINO_BINDER_H
#define ANAKRINO_BINDER_H

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000

#include "BrowserTab.h"
#include "ViewerTab.h"

#include "IconOffsets.h"
#include "InfoView.h"
#include "MicrosoftBar.h"

#include "AboutDialog.h"
#include "resource.h"

#include "anakrino/IBinder.h"
#include "anakrino/IBrowser.h"
#include "anakrino/ITool.h"
#include "anakrino/IViewer.h"

#include "menes-com/Unknown.h"
#include "dialect/IDialect.h"

namespace Anakrino {

class MasterBinder :
	public CFrameWindowImpl<MasterBinder>,
	public CUpdateUI<MasterBinder>,
	//public CMessageFilter,
	public CIdleHandler,
	public Diapexis::Unknown,
	public IBinder
{

	DIAPEXIS_OBJECT(MasterBinder)

	DIAPEXIS_QUERY_BEGIN(MasterBinder)
	DIAPEXIS_QUERY_MAP(Diapexis::Unknown)
	DIAPEXIS_QUERY_MAP(IBinder)
	DIAPEXIS_QUERY_END()

  public:
	DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME)

	CInfoView m_InfoView;

	CCommandBarCtrl m_CmdBar;
	CToolBarCtrl m_ToolBar;
	CStatusBarCtrl m_StatusBar;

	CImageList m_TokenIcons;
	CImageList m_BrowserIcons;

	BrowserTab m_Browsers;
	ViewerTab m_Viewers;

	CSplitterWindow m_VSplitter;
	CHorSplitterWindow m_HSplitter;

	typedef std::vector< Diapexis::Handle<ITool> > ToolVector;
	ToolVector m_Tools;

	typedef std::vector<clsid_t> DialectVector;
	DialectVector m_Dialects;
	int32_t m_CurrentDialect;

	typedef std::map<Metallurgy::Assembly *, int32_t> AssemblyMap;
	typedef std::map<const Metallurgy::Assembly *, DOM_Document> DocumentMap;

	AssemblyMap m_Assemblies;
	DocumentMap m_Documents;

	const Metallurgy::Token *m_TokenRing[10];
	uint32_t m_RingStart;
	uint32_t m_RingCurrent;
	uint32_t m_RingEnd;

	MasterBinder() :
		m_RingStart(0),
		m_RingCurrent(9),
		m_RingEnd(0),
		m_CurrentDialect(-1)
	{
		::ZeroMemory(m_TokenRing, sizeof(m_TokenRing));
	}

	void UpdateBrowser() {
		m_ToolBar.EnableButton(3370, m_RingCurrent != m_RingStart);
		m_ToolBar.EnableButton(3371, m_RingCurrent != (m_RingEnd - 1) % 10);
	}

	void Load(wcstr_t file) {
		CWaitCursor waiting;

		try {
			Metallurgy::Assembly *mAssembly = new Metallurgy::Assembly(file);
            m_Assemblies.insert(AssemblyMap::value_type(mAssembly, 0));
			m_Browsers.Bind(mAssembly);
		} catch (const Dialect::IDialectException &ex) {
			MessageBox(ex.toString().c_str(), L"Dialect Exception");
		} catch (std::wstring &ex) {
			MessageBox(ex.c_str(), L"Miscellaneous Exception");
		}
	}

	/*virtual BOOL PreTranslateMessage(MSG *pMsg) {
		if (CFrameWindowImpl<MasterBinder>::PreTranslateMessage(pMsg))
			return TRUE;
		if (m_Viewers.PreTranslateMessage(pMsg))
			return TRUE;
		if (m_Browsers.PreTranslateMessage(pMsg))
			return TRUE;
		if (m_InfoView.PreTranslateMessage(pMsg))
			return TRUE;
		return FALSE;
	}*/

	virtual BOOL OnIdle() {
		UIUpdateToolBar();
		return FALSE;
	}

	BEGIN_MSG_MAP(MasterBinder)
		MESSAGE_HANDLER(WM_CREATE, OnCreate)
		MESSAGE_HANDLER(WM_CLOSE, OnClose)
		COMMAND_ID_HANDLER(ID_APP_EXIT, OnFileExit)
		COMMAND_ID_HANDLER(ID_FILE_OPEN, OnFileOpen)
		COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
		CHAIN_MSG_MAP(CUpdateUI<MasterBinder>)
		CHAIN_MSG_MAP(CFrameWindowImpl<MasterBinder>)
	
		COMMAND_RANGE_HANDLER(ID_DIALECT_AUTOMATIC, ID_DIALECT_AUTOMATIC + m_Dialects.size(), OnDialect)

		COMMAND_ID_HANDLER(3370, OnBack)
		COMMAND_ID_HANDLER(3371, OnForward)

		REFLECT_NOTIFICATIONS()
	END_MSG_MAP()

	BEGIN_UPDATE_UI_MAP(MasterBinder)
		//UPDATE_ELEMENT(ID_LANGUAGE_CSHARP, UPDUI_MENUPOPUP)
	END_UPDATE_UI_MAP()

	void Select(const Metallurgy::Token *token) {
		if (m_TokenRing[m_RingCurrent] != token) {
			m_RingCurrent = (m_RingCurrent + 1) % 10;
			if (m_RingStart == m_RingEnd)
				m_RingStart = (m_RingCurrent + 1) % 10;
			m_RingEnd = (m_RingCurrent + 1) % 10;
			m_TokenRing[m_RingCurrent] = token;
			UpdateBrowser();
		}

		m_StatusBar.SetText(0, L"");
		try {
			m_InfoView.Select(token);
			m_Viewers.Update(token);
		} catch (const Dialect::IDialectException &ex) {
			m_StatusBar.SetText(0, (L"Dialect Exception: " + ex.toString()).c_str());
		} catch (std::wstring &ex) {
			m_StatusBar.SetText(0, (L"Miscellaneous Exception: " + ex).c_str());
		}
	}

	uint32_t GetIcon(const Metallurgy::Token *token);

	HIMAGELIST GetImageList() {
		return m_TokenIcons;
	}

	clsid_t GetDialect(const Metallurgy::Token *token) {
		if (m_CurrentDialect == -1)
			return m_Dialects[0];
		return m_Dialects[m_CurrentDialect];
	}

	void ShowContext(const Metallurgy::Token *token);
	std::wstring GetDisplayText(const Metallurgy::Token *token);
	int CompareToken(const Metallurgy::Token *ltoken, const Metallurgy::Token *rtoken);
	void XmlDocument(const Metallurgy::Token *token, DOM_Node &node);
	const Metallurgy::TypeDef *Resolve(const Metallurgy::Type *type);

	LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);

	LRESULT OnBack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
		Select(m_TokenRing[m_RingCurrent = (m_RingCurrent - 1) % 10]);
		UpdateBrowser();
		return 0;
	}

	LRESULT OnForward(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
		Select(m_TokenRing[m_RingCurrent = (m_RingCurrent + 1) % 10]);
		UpdateBrowser();
		return 0;
	}

	void SetViewer(IViewer *viewer) {
	}

	LRESULT OnDialect(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
		m_CurrentDialect = wID - ID_DIALECT_AUTOMATIC - 1;
		/*if (m_CurrentViewer != -1)
			//m_Viewers[m_CurrentViewer]->Select(m_TokenRing[m_RingCurrent]);
			Select(m_TokenRing[m_RingCurrent]);*/
		m_Browsers.Refresh();

		CMenuHandle menu = m_CmdBar.GetMenu();
		CMenuHandle dialects = menu.GetSubMenu(1);
		dialects.CheckMenuRadioItem(ID_DIALECT_AUTOMATIC, ID_DIALECT_AUTOMATIC + m_Dialects.size(), wID, MF_BYCOMMAND);
		return 0;
	}

	LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) {
		m_Browsers.Destroy();
		for (AssemblyMap::iterator assembly(m_Assemblies.begin()); assembly != m_Assemblies.end(); assembly++)
			delete assembly->first;
		DestroyWindow();
		return 0;
	}

	LRESULT OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
		PostMessage(WM_CLOSE);
		return TRUE;
	}

	LRESULT OnFileOpen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
		CFileDialog dialog(TRUE, L"dll", NULL, OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST /*| OFN_DONTADDTORECENT*/, L"Assembly Manifests (.dll,.exe)\0*.DLL;*.EXE\0");
		if (dialog.DoModal() == IDOK) {
			Load(dialog.m_szFileName);
			m_StatusBar.SetText(0, dialog.m_szFileName);
		}
		return 0;
	}

	LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
		CAboutDlg about;
		about.DoModal();
		return 0;
	}
};

}

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}

#endif//ANAKRINO_BINDER_H