#include "gui.h"

const string TkGui::dbName="frmdb.xml";


const char* TkGui::type="TkGui";

const char* TkGui::getType() const
{
	return type;
}

TkGui::const_iterator TkGui::begin()
{
	return base.begin();
}

TkGui::const_iterator TkGui::end()
{
	return base.end();
}

TkGui::TkGui(TclInterp* interp)
{
	this->interp=interp;
	mainWindow=TkTopLevel::createMainWindow(interp);
}

void TkGui::destroy()
{
	for(t_base::iterator it=base.begin();it!=base.end();it++)
	{
        (*it)->destroy();
	}
	base.clear();
}

void TkGui::load()
{
	TiXmlDocument doc;
	doc.LoadFile(dbName.c_str());
	if (doc.Error()) return;
	TiXmlElement* node=doc.FirstChildElement();
	while(node!=0)
	{
		Ptr<TkTopLevel> topLevel=(TkTopLevel*)TXmlObject::getXmlObject(*node);
		base.push_back(topLevel);
		node=node->NextSiblingElement();

		topLevel->setWindowState(TkWinStateOption::withdrawn);
		topLevel->create();
		topLevel->doLayout();
	}
}

void TkGui::save() const
{
	TiXmlDocument doc;
	for(t_base::const_iterator it=base.begin();it!=base.end();it++)
	{
		TiXmlElement& element=(*it)->serialize();
		doc.InsertEndChild(element);
	}
	doc.SaveFile(dbName.c_str());
}

void TkGui::insertSourceForm(TkTopLevel* topLevel)
{
	base.push_back(topLevel);
}

void TkGui::deleteSourceForm(TkTopLevel* topLevel)
{
	for(t_base::iterator it=base.begin();it!=base.end();it++)
	{
		if (*it==topLevel)
		{
			topLevel->destroy();
			base.erase(it);
			return;
		}
	}
}

TkGui::t_base& TkGui::getSourceForms()
{
	return base;
}
	
Ptr<TkTopLevel>& TkGui::getSourceForm(const string& name)
{
	for(t_base::iterator it=base.begin();it!=base.end();it++)
	{
           if ((*it)->getName()==name) return *it;
	}
	return *(new Ptr<TkTopLevel>());
}

Ptr<TkTopLevel>& TkGui::cloneSourceForm(const string& name)
{
	Ptr<TkTopLevel>& sourceFrm=getSourceForm(name);
	if (sourceFrm.isNull()) return sourceFrm;
	
	TkTopLevel* clonedFrm=(TkTopLevel*)sourceFrm->clone();
	
	return *(new Ptr<TkTopLevel>(clonedFrm));
}


