/////////////////////////////////////////////////////////////////////////////
// Name:        No names yet.
// Purpose:     Contrib. demo
// Author:      Aleksandras Gluchovas
// Modified by:
// Created:     2000/02/08
// RCS-ID:      
// Copyright:   (c) Aleksandras Gluchovas
// Licence:   	GPL (version 2.0 or later)
/////////////////////////////////////////////////////////////////////////////

#ifdef __GNUG__
    #pragma implementation "minimal.cpp"
    #pragma interface "minimal.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif

#include "resbrowser.h"
#include "res_doc.h"
#include "dmbrowser.h"

#include "mimetypes.h"

/***** Implementation for class ResSectionInfo *****/

ResSectionInfo::ResSectionInfo()

	: mpItem( NULL ),
	  mpHandler( NULL )

{}

ResSectionInfo::ResSectionInfo( const wxString& resClass, const wxString& displayName )

	: mResClassName( resClass ),
	  mDisplayName( displayName ),
	  mpItem( NULL ),
	  mpHandler( NULL )
{}

/***** Implementation for class ResourceBrowser *****/

IMPLEMENT_DYNAMIC_CLASS( ResourceBrowser, wxPMPane )

BEGIN_EVENT_TABLE( ResourceBrowser, wxPMPane )
END_EVENT_TABLE()

ResourceBrowser::ResourceBrowser()

	: mpPrj( NULL )
{
	mDocTypes.Add( wxwMIME_MENUBAR_RESOURCE );
	mDocTypes.Add( wxwMIME_WIDGET_RESOURCE );

	mpTree = NULL;
}

ResourceBrowser::~ResourceBrowser()
{
}

bool ResourceBrowser::Start()
{
	return TRUE;
}

bool ResourceBrowser::Stop()
{
	if ( mpTree ) delete mpTree;

	return TRUE;
}

wxWindow* ResourceBrowser::GetPaneWindow()
{
	return mpTree;
}

void ResourceBrowser::CreatePaneWindow( wxWindow* pParent )
{
	mpTree = new wxTSTree( pParent );

	mpTree->RegisterHandler( this );
	CreateImageList( TRUE );

	mpPrj = wxPMBootSvc().GetWorkplace()->GetActiveProject();

	wxString name = "default";
	
	if ( mpPrj->CanHaveFile() )
		
		name = mpPrj->GetFileInfo()->GetNameWithoutExtension();

	name += " resources";

	wxTreeItemId rootItem = mpTree->AddTSRoot( name, ID_BMP_WKP, -1, 
											   new wxTSItemData( NULL, this, ID_RESOURCE_ROOT ) );

	mpTree->SetItemHasChildren( rootItem ); 

	this->SetOwnedBranchItem( rootItem );

	mpTree->SetItemBold( rootItem );
}

wxStringList* ResourceBrowser::GetDocumentTypes()
{
	return &mDocTypes;
}

wxEvtHandler* ResourceBrowser::GetEvtHandler()
{
	return this;
}

void ResourceBrowser::OnBranchItemExpanding( wxTreeItemId id , wxTSItemData* pData )
{
	if ( pData->GetType() == ID_RESOURCE_ROOT && 
		 mpTree->GetChildrenCount( id ) == 0 )
	{
		mSectionCount = 6;
		mpSections = new ResSectionInfo[ mSectionCount ];

		mpSections[0].mDisplayName = "Dialogs";
		mpSections[0].mResClassName  = "wxDialog";

		mpSections[1].mDisplayName = "Frames";
		mpSections[1].mResClassName  = "wxFrame";

		mpSections[2].mDisplayName = "MenuBars";
		mpSections[2].mResClassName  = "wxMenuBar";

		mpSections[3].mDisplayName = "Panels";
		mpSections[3].mResClassName  = "wxPanel";

		mpSections[4].mDisplayName = "ToolBars";
		mpSections[4].mResClassName  = "wxToolBar";

		mpSections[5].mDisplayName = "Bitmaps";
		mpSections[5].mResClassName  = "wxBitmap";

		size_t i;
		for( i = 0; i != (unsigned int)mSectionCount; ++i )
		{
			mpSections[i].mpItem = new wxTSItemData( NULL, this, ID_SECTION_FOLDER );
			mpTree->AppendTSItem( id, mpSections[i].mDisplayName,  ID_BMP_FOLDER, ID_BMP_FOLDER, 
								  mpSections[i].mpItem );
		}

		PMFileInfoListT& files = mpPrj->GetFiles();

		for( i = 0; i != files.Count(); ++i )
		{
			wxPMFileInfo& file = *files[i];

			if ( file.GetType() == wxwMIME_WX_RESOURCE )
			//if ( file.GetType() == "text/xml" )   //glt ???? not a registered type in mimetypes.h @@@@@@@@@
			{
				ResDocument* pDoc = (ResDocument*)
					wxPMBootSvc().GetDocManager()->OpenDocument( file, mpPrj, FALSE );

				Record* pRoot = pDoc->GetRootRecord();

                size_t n;
				for( n = 0; n != pRoot->GetFieldCount(); ++n )
				{
					Record& child = pRoot->GetRecordByIndex( n );
					wxString resClass = child[ "class" ];

                    size_t k;
					for( k = 0; k != (unsigned int)mSectionCount; ++k )
					{
						ResSectionInfo& sect = mpSections[k];

						if ( sect.mResClassName == resClass )
						{
							WidgetResTemplate* pTempl = 
								pDoc->GetTemplateManager().FindWidgetTemplateForClass( resClass );

							wxTreeItemId id = 
								mpTree->AppendTSItem( sect.mpItem->GetId(), child["name"], 
													  pTempl->mBitmapId, -1, 
													  new wxTSItemData( pDoc, this, ID_RESOURCE_ITEM ), FALSE );

							mpTree->SetItemHasChildren( id );
							
							break;
						}
					}
				}
			}
		}
	}
	else
	if ( pData->GetType() == ID_RESOURCE_ITEM )
	{
		// resource-item is being expanded, load it into a document for editing

		ResDocument* pDoc = (ResDocument*)pData->GetObject();

		ResItemDocumentBase* pItemDoc = pDoc->ActivateEditorForItem( mpTree->GetItemText( id ) );

		if ( pItemDoc )
		{
			DMNodeTreeHandler* pHandler = new DMNodeTreeHandler( pItemDoc );
			mpTree->RegisterHandler( pHandler );

			pData->SetHandler( pHandler );
			pHandler->SetOwnedBranchItem( id );

			wxDMNode* pRoot = pItemDoc->GetRootNode();

			pData->SetObject( pRoot );
			mpTree->HashObject( pRoot, id );

			pHandler->OnBranchItemExpanding( id, pData );

			pRoot->GetCommandProcessor()->AddListener( pHandler );

			// FIXME:: destruction of branch-handlers
		}
	}
}

void ResourceBrowser::AddDocumentType( const wxString& type )
{
	mDocTypes.Add( type );
}

void ResourceBrowser::RemoveDocumentType( const wxString& type )
{
	mDocTypes.Delete( type );
}

/*** protectec methods ***/

void ResourceBrowser::CreateImageList( bool withResourceIcons )
{
	TSImageInfoListT icons;

	icons.Add( new wxTSImageInfo( wxPMBmpMgr().FindBitmap( "browsers/16x16_wxlogo_45_degrees" ), ID_BMP_WKP, *wxRED ) );
	icons.Add( new wxTSImageInfo( wxPMBmpMgr().FindBitmap( "browsers/16x16_folder_blue" ),  	 ID_BMP_FOLDER, *wxRED ) );

	if ( withResourceIcons )
	{
		ResTemplateManager& mgr = ResDocument::GetTemplateManager();

		WidgetResTemplateListT& lst = mgr.GetTemplates();

        size_t i;
		for( i = 0; i != lst.Count(); ++i )
		{
			WidgetResTemplate& templ = *lst[i];
			templ.mBitmapId = ID_BMP_FOLDER + 1 + i;

			if ( templ.mToolBarBitmap.Ok() )
			
				icons.Add( 
					new wxTSImageInfo(  wxPMBmpMgr().CloneBitmapCopy( templ.mToolBarBitmap ),
										templ.mBitmapId, *wxRED ) );
		}
	}

	mpTree->RegisterIcons( icons, this );
	mpTree->RebuildImageList();

	if ( withResourceIcons )
	{
		ResTemplateManager& mgr = ResDocument::GetTemplateManager();

		WidgetResTemplateListT& lst = mgr.GetTemplates();

        size_t i;
		for( i = 0; i != lst.Count(); ++i )
		{
			WidgetResTemplate& templ = *lst[i];

			if ( templ.mToolBarBitmap.Ok() )

				templ.mBitmapId = mpTree->GetActualImageId( ID_BMP_FOLDER + 1 + i, this );
		}
	}
}

/***** Implementation for class DMNodeTreeHandler *****/

IMPLEMENT_DYNAMIC_CLASS( DMNodeTreeHandler, wxEvtHandler )

BEGIN_EVENT_TABLE( DMNodeTreeHandler, wxEvtHandler )

	EVT_MENU( ID_NEW,			DMNodeTreeHandler::OnNew )

END_EVENT_TABLE()

DMNodeTreeHandler::DMNodeTreeHandler()

	: mpDoc( NULL )
{}

DMNodeTreeHandler::DMNodeTreeHandler( ResItemDocumentBase* pDoc )

	: mpDoc( pDoc )
{}

DMNodeTreeHandler::~DMNodeTreeHandler()
{
}

// overriden methods of wxTSBranchHandler 

wxEvtHandler* DMNodeTreeHandler::GetEvtHandler()
{
	return this;
}

void DMNodeTreeHandler::OnBranchItemExpanding( wxTreeItemId id, wxTSItemData* pData )
{
	if ( id == this->GetOwnedBranchItem() &&
		 mpTree->GetChildrenCount( id ) == 0 )
	
		 CreateBranchForNode( mpDoc->GetRootNode() );
}

void DMNodeTreeHandler::OnAddItemsToPopup( wxMenu* pMenu )
{
	if ( mpTree->GetSelectedObject() &&
		 ((wxDMNode*)mpTree->GetSelectedObject())->GetParent() == NULL )
	{
		wxDMNode* pNode = (wxDMNode*)mpTree->GetSelectedObject();

		WidgetResTemplate* pTempl = mpDoc->GetTemplateForNode( *pNode );

		pMenu->Append( ID_NEW, "New " + pTempl->mTag );
		pMenu->AppendSeparator();

		pMenu->Append( wxDMNodeCommandHandler::ID_DELETE, "&Delete" );
	}
	else
	{
		mpDMHandler->AddMenuCommands( pMenu );
	}
}

void DMNodeTreeHandler::OnSelectionChanged( wxTreeItemId id, wxTSItemData* pData )
{
	wxDMNode* pNode = (wxDMNode*)pData->GetObject();

	if ( pNode )
	{
		if ( wxPMBootSvc().GetDocManager()->GetCurrentView() != 
			 mpDoc->GetFirstView() )

			 wxPMBootSvc().GetDocManager()->ActivateDocument( mpDoc );

		DMNodeListT lst;
		lst.Add( pNode );
		pNode->SetSelection( lst );

		if ( wxWindow::FindFocus() != mpTree )

			mpTree->SetFocus();
	}
}

void DMNodeTreeHandler::CreateBranchForNode( wxDMNode* pNode )
{
	if ( pNode->GetParent() )
	{
		WidgetResTemplate* pTempl = mpDoc->GetTemplateForNode( *pNode );

		int order = pNode->GetOrderNo();

		if ( pTempl )

			mpTree->AppendTSItem( mpTree->FindTreeItemForObject( pNode->GetParent() ), 
								  pNode->GetDisplayName(), pTempl->mBitmapId, -1, 
								  new wxTSItemData( pNode, this), FALSE, order
								);
	}

    size_t i;
	for( i = 0; i != pNode->GetChildCount(); ++i )
	{
		wxDMNode& child = *pNode->GetChild( i );

		CreateBranchForNode( &child );
	}
}

/*** event handlers ***/

void DMNodeTreeHandler::OnNew( wxCommandEvent& event )
{
	// TBD::
}

void DMNodeTreeHandler::OnNodeRemoved( wxDMNode& node )
{
	mpTree->DeleteBranch( mpTree->FindTreeItemForObject( &node ) );
}

void DMNodeTreeHandler::OnNodeAdded( wxDMNode& node )
{
	CreateBranchForNode( &node );
}

void DMNodeTreeHandler::OnNodeChanged( wxDMNode& node )
{
	wxTreeItemId id = mpTree->FindTreeItemForObject( &node );

	mpTree->SetItemText( id, node.GetDisplayName() );
}

void DMNodeTreeHandler::OnNodeOrderChanged( wxDMNode& node )
{
}

void DMNodeTreeHandler::OnNodeReplaced( wxDMNode& node, wxDMNode& withNode )
{
	// FOR NOW:: inefficient

	OnNodeRemoved( node );
	OnNodeAdded( withNode );
}

void DMNodeTreeHandler::OnFocusChanged( wxDMNode& node )
{
	wxTreeItemId id = mpTree->FindTreeItemForObject( &node );

	mpTree->EnsureVisible( id );

	mpTree->SelectItem( id );
}

void DMNodeTreeHandler::OnFocusRemoved()
{
}

