#include "frmlist.h"

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

class MyWindowListener:public TkTopLevelListener
{
public:
	void onDestroy(TkTopLevel* source)
	{
		source->setWindowState(TkWinStateOption::withdrawn);
	}
};

FrmList::FrmList(Ptr<TclInterp>& interp,Designer* designer):designer(designer),interp(interp)
{
	butOpen=new TkButton(interp,"open");
	butDel=new TkButton(interp,"delete");

	window=new TkTopLevel(interp);
	window->setTitle("Forms");
	window->setWindowListener(new MyWindowListener());
	lstForms=new TkListbox(interp);
	reloadList();
	window->setBounds(200,200,0,510);
	window->setLayoutManager(new TkGridLayout());
	window->addChild(lstForms,new TkGridConstraints(0,0,5,2));
	window->addChild(butOpen,new TkGridConstraints(6,0,TkGridConstraints::EAST|TkGridConstraints::WEST));
	window->addChild(butDel,new TkGridConstraints(6,1,TkGridConstraints::EAST|TkGridConstraints::WEST));
	window->create();
	window->doLayout();
		
	butOpen->addButtonPressListener(this);
	butDel->addButtonPressListener(this);
}

void FrmList::onButtonPress(EHeader& header,int button,const string& state,int x,int y,int x_root,int y_root)
{
	if (lstForms->getCursor()==-1) return;
	if (header.source==butDel.asObject())
	{
		Ptr<TkTopLevel>& form=designer->getGui()->getSourceForms()[lstForms->getCursor()];
		designer->getGui()->deleteSourceForm((TkTopLevel*)form.asObject());

		lstForms->getDefaultVariable()->remove(lstForms->getCursor());
		return;
	}
	if (header.source==butOpen.asObject())
	{
		Ptr<TkTopLevel>& form=designer->getGui()->getSourceForms()[lstForms->getCursor()];
		form->setWindowState(TkWinStateOption::normal);
		designer->getAppWindow()->enlistWindow(form);
		return;
	}
}

void FrmList::reloadList()
{
	lstForms->getDefaultVariable()->clear();
	for(TkGui::const_iterator it=designer->getGui()->begin();it!=designer->getGui()->end();it++)
	{
		lstForms->getDefaultVariable()->push_back((*it)->getName());
	}
}

void FrmList::setVisible(bool value)
{
	if (value) 
		window->setWindowState(TkWinStateOption::normal);
	else
		window->setWindowState(TkWinStateOption::withdrawn);
}
