//=============================================================================//
//   File : toolbareditor.cpp
//   Created on Wed 01 Dec 2004 14:42:20 by Szymon Stefanek
//
//   This file is part of the KVIrc IRC client distribution
//   Copyright (C) 2004 Szymon Stefanek <pragma at kvirc dot net>
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your opinion) any later version.
//
//   This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc. ,51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================

#include "toolbareditor.h"
#include "kvi_actiondrawer.h"
#include "kvi_locale.h"
#include "kvi_frame.h"
#include "kvi_iconmanager.h"
#include "kvi_actionmanager.h"
#include "kvi_customtoolbar.h"
#include "kvi_customtoolbarmanager.h"
#include "kvi_customtoolbardescriptor.h"
#include "kvi_imagedialog.h"
#include "kvi_fileutils.h"
#include "kvi_filedialog.h"
#include "kvi_kvs_useraction.h"
#include "kvi_draganddrop.h"

#include <tqpushbutton.h>
#include <tqlayout.h>
#include <tqapplication.h>
#include <tqtooltip.h>

#include <tqlineedit.h>
#include <tqlabel.h>
#include <tqmessagebox.h>
#include <tqframe.h>
#include <tqdir.h>
#include <tqtimer.h>
#include <tqevent.h>

KviCustomizeToolBarsDialog * KviCustomizeToolBarsDialog::m_pInstance = 0;
extern TQRect g_rectToolBarEditorDialogGeometry;



KviTrashcanLabel::KviTrashcanLabel(TQWidget * p)
: TQLabel(p)
{
	setPixmap(*(g_pIconManager->getBigIcon("kvi_bigicon_trashcan.png")));
	TQToolTip::add(this,__tr2qs("Drop here the icons from the toolbars to remove them"));
	setFrameStyle(TQFrame::Sunken | TQFrame::WinPanel);
	setAcceptDrops(true);
	setAlignment(TQt::AlignCenter);
	setMinimumSize(40,40);
	m_uFlashCount = 0;
	m_pFlashTimer = 0;
	m_clrOriginal = paletteBackgroundColor();
	connect(KviActionManager::instance(),TQ_SIGNAL(removeActionsHintRequest()),this,TQ_SLOT(flash()));
}

KviTrashcanLabel::~KviTrashcanLabel()
{
	if(m_pFlashTimer)
	{
		m_pFlashTimer->stop();
		delete m_pFlashTimer;
	}
}

void KviTrashcanLabel::flash()
{
	m_uFlashCount = 0;
	if(m_pFlashTimer)return;
	m_pFlashTimer = new TQTimer();
	connect(m_pFlashTimer,TQ_SIGNAL(timeout()),this,TQ_SLOT(heartbeat()));
	m_pFlashTimer->start(200);
}

void KviTrashcanLabel::heartbeat()
{
	m_uFlashCount++;
	if(m_uFlashCount % 2)
		setPaletteBackgroundColor(TQColor(0,0,0));
	else
		setPaletteBackgroundColor(m_clrOriginal);
	update();
	if(m_uFlashCount == 8)
	{
		m_pFlashTimer->stop();
		delete m_pFlashTimer;
		m_pFlashTimer = 0;
	}
}

void KviTrashcanLabel::dropEvent(TQDropEvent * e)
{
	if(KviTextDrag::canDecode(e))
		e->accept();
}

void KviTrashcanLabel::dragEnterEvent(TQDragEnterEvent * e)
{
	TQString s;
	if(KviTextDrag::decode(e,s))
		e->accept();
}



KviCustomToolBarPropertiesDialog::KviCustomToolBarPropertiesDialog(TQWidget * p,const TQString &szText,const TQString &szId,const TQString &szLabel,const TQString &szIconId)
: TQDialog(p)
{
	m_szId = szId;
	m_szOriginalId = szId;
	m_szLabel = szLabel;

	setCaption(__tr2qs("ToolBar Properties"));
	setIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_TOOLBAR)));
	
	TQGridLayout * g = new TQGridLayout(this,5,6,5,3);
	
	TQLabel * l = new TQLabel(szText,this);
	g->addMultiCellWidget(l,0,0,0,5);

	l = new TQLabel(__tr2qs("Label") + ":",this);
	g->addWidget(l,1,0);

	m_pLabelEdit = new TQLineEdit(this);
	g->addMultiCellWidget(m_pLabelEdit,1,1,1,5);
	m_pLabelEdit->setText(szLabel);
	connect(m_pLabelEdit,TQ_SIGNAL(textChanged(const TQString &)),this,TQ_SLOT(labelTextChanged(const TQString &)));
	
	l = new TQLabel(__tr2qs("Icon") + ":",this);
	g->addWidget(l,2,0);
	
	m_pIconEdit = new TQLineEdit(this);
	m_pIconEdit->setReadOnly(true);
	g->addMultiCellWidget(m_pIconEdit,2,2,1,4);
	
	m_pIconButton = new TQPushButton(this);
	g->addMultiCellWidget(m_pIconButton,2,2,5,5);
	connect(m_pIconButton,TQ_SIGNAL(clicked()),this,TQ_SLOT(iconButtonClicked()));

	iconSelected(szIconId);

	m_pAdvanced = new TQWidget(this);
	TQGridLayout * ag = new TQGridLayout(m_pAdvanced,1,2,0,3);

	l = new TQLabel(__tr2qs("Id") + ":",m_pAdvanced);
	l->setMinimumWidth(100);
	ag->addWidget(l,0,0);

	m_pIdEdit = new TQLineEdit(m_pAdvanced);
	ag->addWidget(m_pIdEdit,0,1);
	ag->setRowStretch(0,1);

	m_pIdEdit->setText(szId);

	g->addMultiCellWidget(m_pAdvanced,3,3,0,5);
	m_pAdvanced->hide();

	m_pLabelEdit->setFocus();
	
	TQPushButton * pb = new TQPushButton(__tr2qs("OK"),this);
	connect(pb,TQ_SIGNAL(clicked()),this,TQ_SLOT(okClicked()));
	pb->setMinimumWidth(80);
	g->addMultiCellWidget(pb,4,4,4,5);
	
	pb = new TQPushButton(__tr2qs("Cancel"),this);
	connect(pb,TQ_SIGNAL(clicked()),this,TQ_SLOT(reject()));
	pb->setMinimumWidth(80);
	g->addWidget(pb,4,3);
	
	m_pAdvancedButton = new TQPushButton(__tr2qs("Advanced..."),this);
	connect(m_pAdvancedButton,TQ_SIGNAL(clicked()),this,TQ_SLOT(advancedClicked()));
	m_pAdvancedButton->setMinimumWidth(100);
	g->addMultiCellWidget(m_pAdvancedButton,4,4,0,1);
	
	g->setRowStretch(0,1);
	g->setColStretch(2,1);


}

KviCustomToolBarPropertiesDialog::~KviCustomToolBarPropertiesDialog()
{
}

void KviCustomToolBarPropertiesDialog::iconSelected(const TQString &szIconId)
{
	TQPixmap * p = g_pIconManager->getImage(szIconId);
	if(p)
	{
		m_pIconButton->setPixmap(*p);
		m_szIconId = szIconId;
		m_pIconEdit->setText(szIconId);
	} else {
		m_pIconButton->setText("...");
		m_szIconId = "";
		m_pIconEdit->setText("");
	}
}

void KviCustomToolBarPropertiesDialog::iconButtonClicked()
{
	KviImageDialog * dlg = new KviImageDialog(this,__tr2qs("Please choose the icon for the ToolBar"));
	if(dlg->exec() != TQDialog::Accepted)
	{
		delete dlg;
		return;
	}
	TQString s = dlg->selectedImage();
	delete dlg;
	iconSelected(s);
}


void KviCustomToolBarPropertiesDialog::labelTextChanged(const TQString &s)
{
	if(m_szOriginalId.isEmpty())
	{
		TQString szId = KviCustomToolBarManager::instance()->idForNewToolBar(s);
		m_pIdEdit->setText(szId);
	}
}


void KviCustomToolBarPropertiesDialog::okClicked()
{
	if(m_szLabel.isEmpty())
	{
		TQMessageBox::information(this,__tr2qs("Invalid ToolBar Label"),__tr2qs("The ToolBar Label can't be empty!"),__tr2qs("OK"));
		return;
	}
	
	if(m_szId.isEmpty())
	{
		m_szId = KviCustomToolBarManager::instance()->idForNewToolBar(m_szLabel);
	}
	
	if(KviCustomToolBarManager::instance()->find(m_szId))
	{
		if(m_szId != m_szOriginalId)
		{
			if(TQMessageBox::information(this,__tr2qs("Duplicate ToolBar Id"),
				__tr2qs("The specified ToolBar Id already exists.<br>" \
					"Would you like KVIrc to assign it automatically (so it doesn't "
					"collide with any other toolbar) or you prefer to do it manually ?"),
				__tr2qs("Manually"),__tr2qs("Automatically")) == 0)return;
			m_szId = KviCustomToolBarManager::instance()->idForNewToolBar(m_szLabel);
		}
	}

	m_szId = m_pIdEdit->text();
	m_szLabel = m_pLabelEdit->text();
	accept();
}

void KviCustomToolBarPropertiesDialog::advancedClicked()
{
	if(m_pAdvanced->isVisible())
	{
		m_pAdvanced->hide();
		m_pAdvancedButton->setText(__tr2qs("Advanced..."));
	} else {
		m_pAdvanced->show();
		m_pAdvancedButton->setText(__tr2qs("Hide Advanced"));
	}

}


KviCustomizeToolBarsDialog::KviCustomizeToolBarsDialog(TQWidget * p)
: TQDialog(p,"" /*,WType_TopLevel | WStyle_Customize | WStyle_Title | WStyle_StaysOnTop | WStyle_DialogBorder*/)
{
	setCaption(__tr2qs("Customize Toolbars"));
	setIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_TOOLBAR)));

	m_pInstance = this;

	TQGridLayout * g = new TQGridLayout(this,8,2,4,5);
	m_pDrawer = new KviActionDrawer(this);
	g->addMultiCellWidget(m_pDrawer,0,6,0,0);

	TQPushButton * b = new TQPushButton(__tr2qs("New ToolBar"),this);
	connect(b,TQ_SIGNAL(clicked()),this,TQ_SLOT(newToolBar()));
	g->addWidget(b,0,1);

	m_pDeleteToolBarButton = new TQPushButton(__tr2qs("Delete ToolBar"),this);
	connect(m_pDeleteToolBarButton,TQ_SIGNAL(clicked()),this,TQ_SLOT(deleteToolBar()));
	g->addWidget(m_pDeleteToolBarButton,1,1);

	m_pRenameToolBarButton = new TQPushButton(__tr2qs("Edit ToolBar"),this);
	connect(m_pRenameToolBarButton,TQ_SIGNAL(clicked()),this,TQ_SLOT(renameToolBar()));
	g->addWidget(m_pRenameToolBarButton,2,1);

	TQFrame * f = new TQFrame(this);
	f->setFrameStyle(TQFrame::HLine | TQFrame::Sunken);
	g->addWidget(f,3,1);
	
	m_pExportToolBarButton = new TQPushButton(__tr2qs("Export ToolBar"),this);
	connect(m_pExportToolBarButton,TQ_SIGNAL(clicked()),this,TQ_SLOT(exportToolBar()));
	g->addWidget(m_pExportToolBarButton,4,1);

	KviTrashcanLabel * t = new KviTrashcanLabel(this);
	g->addWidget(t,6,1);

	b = new TQPushButton(__tr2qs("Close"),this);
	connect(b,TQ_SIGNAL(clicked()),this,TQ_SLOT(closeClicked()));
	g->addWidget(b,7,1);

	g->setRowStretch(5,1);
	g->setColStretch(0,1);
	
	m_pDrawer->fill();

	connect(KviActionManager::instance(),TQ_SIGNAL(currentToolBarChanged()),this,TQ_SLOT(currentToolBarChanged()));
	KviActionManager::instance()->customizeToolBarsDialogCreated();
	
	currentToolBarChanged();

	if(g_rectToolBarEditorDialogGeometry.y() < 5)
	{
		g_rectToolBarEditorDialogGeometry.setY(5);
	}
	//setGeometry(KVI_OPTION_RECT(KviOption_rectRegisteredUsersDialogGeometry));
	resize(g_rectToolBarEditorDialogGeometry.width(),
		g_rectToolBarEditorDialogGeometry.height());
	move(g_rectToolBarEditorDialogGeometry.x(),
		g_rectToolBarEditorDialogGeometry.y());
}

KviCustomizeToolBarsDialog::~KviCustomizeToolBarsDialog()
{
	g_rectToolBarEditorDialogGeometry = TQRect(pos().x(),pos().y(),size().width(),size().height());

	KviActionManager::instance()->customizeToolBarsDialogDestroyed();
	m_pInstance = 0;
}

void KviCustomizeToolBarsDialog::currentToolBarChanged()
{
	m_pDeleteToolBarButton->setEnabled(KviActionManager::instance()->currentToolBar());
	m_pRenameToolBarButton->setEnabled(KviActionManager::instance()->currentToolBar());
}

void KviCustomizeToolBarsDialog::showEvent(TQShowEvent * e)
{
//	repaintContents();
//	TQRect r = parentWidget() ? parentWidget()->rect() : TQApplication::desktop()->rect();
//	int x = (r.width() - width()) / 2;
//	int y = (r.height() - height()) / 2;
//	move(x,y);
}


void KviCustomizeToolBarsDialog::deleteToolBar()
{
	KviCustomToolBar * t = KviActionManager::currentToolBar();
	if(!t)return;
	if(TQMessageBox::question(this,
			__tr2qs("Confirm ToolBar Deletion"),
			__tr2qs("Do you really want to delete toolbar \"%1\" ?").arg(t->label()),
			__tr2qs("No"),
			__tr2qs("Yes")) == 0)return;
	KviCustomToolBarManager::instance()->destroyDescriptor(t->descriptor()->id());
}

void KviCustomizeToolBarsDialog::exportToolBar()
{
	KviCustomToolBar * t = KviActionManager::currentToolBar();
	if(!t)return;

	TQString szName = TQDir::homeDirPath();
	if(!szName.endsWith(TQString(KVI_PATH_SEPARATOR)))szName += KVI_PATH_SEPARATOR;
	szName += t->descriptor()->id();
	szName += ".kvs";
	
	TQString szFile;
	
	if(!KviFileDialog::askForSaveFileName(szFile,__tr2qs("Choose a Filename - KVIrc"),szName,"*.kvs",true,true,true))return;

	TQString szCode;

	int ret = TQMessageBox::question(this,
			__tr2qs("ToolBar Export"),
			__tr2qs("Do you want the associated actions to be exported with the toolbar ?"),
			__tr2qs("Yes"),
			__tr2qs("No"),
			__tr2qs("Cancel"));

	if(ret == 2)return;

	bool bExportActions = ret == 0;

	if(bExportActions)
	{
		KviPointerList<TQString> * a = t->descriptor()->actions();
		if(a)
		{
			for(TQString * s = a->first();s;s = a->next())
			{
				KviAction * act = KviActionManager::instance()->getAction(*s);
				if(act)
				{
					if(act->isKviUserActionNeverOverrideThis())
					{
						((KviKvsUserAction *)act)->exportToKvs(szCode);
						szCode += "\n\n";
					}
				}
			}
		}
	}

	szCode += "toolbar.create ";
	szCode += t->descriptor()->id();
	szCode += " ";
	szCode += t->descriptor()->labelCode();
	szCode += " ";
	szCode += t->descriptor()->iconId();
	szCode += "\n";

	KviPointerList<TQString> * aa = t->descriptor()->actions();
	if(aa)
	{
		for(TQString * ss = aa->first();ss;ss = aa->next())
		{
			szCode += "toolbar.additem ";
			szCode += t->descriptor()->id();
			szCode += " ";
			szCode += *ss;
			szCode += "\n";
		}
	}

	szCode += "toolbar.show ";
	szCode += t->descriptor()->id();
	szCode += "\n";

	if(!KviFileUtils::writeFile(szFile,szCode))
	{
		TQMessageBox::warning(this,__tr2qs("Write Failed - KVIrc"),__tr2qs("Unable to write to the toolbar file."),__tr2qs("OK"));
	}

}

void KviCustomizeToolBarsDialog::renameToolBar()
{
	KviCustomToolBar * t = KviActionManager::currentToolBar();
	if(!t)return;

	KviCustomToolBarPropertiesDialog * dlg = new KviCustomToolBarPropertiesDialog(this,
		__tr2qs("Please specify the properties for the toolbar \"%1\"").arg(t->label()),
		t->descriptor()->id(),
		t->descriptor()->labelCode(),
		t->descriptor()->iconId());

	dlg->show();
	if(dlg->exec() != TQDialog::Accepted)
	{
		delete dlg;
		return;
	}

	TQString id = dlg->id();
	TQString label = dlg->label();
	TQString icon = dlg->iconId();
	delete dlg;

	if((id == t->descriptor()->id()) && (label == t->descriptor()->labelCode()) && (icon == t->descriptor()->iconId()))return;

	KviCustomToolBarManager::instance()->renameDescriptor(t->descriptor()->id(),id,label);
	t->descriptor()->setIconId(icon);
}

void KviCustomizeToolBarsDialog::newToolBar()
{
	KviCustomToolBarPropertiesDialog * dlg = new KviCustomToolBarPropertiesDialog(this,
		__tr2qs("Please specify the properties for the new toolbar"),
		KviCustomToolBarManager::instance()->idForNewToolBar(__tr2qs("My ToolBar")),
		__tr2qs("My ToolBar"));

	dlg->show();
	if(dlg->exec() != TQDialog::Accepted)
	{
		delete dlg;
		return;
	}

	TQString id = dlg->id();
	TQString label = dlg->label();
	TQString icon = dlg->iconId();
	delete dlg;

	KviCustomToolBarDescriptor * d = KviCustomToolBarManager::instance()->create(id,label);
	d->setIconId(icon);
	KviCustomToolBar * t = d->createToolBar();
	KviActionManager::instance()->setCurrentToolBar(t);
}

void KviCustomizeToolBarsDialog::closeClicked()
{
	delete this;
}

void KviCustomizeToolBarsDialog::cleanup()
{
	if(!m_pInstance)return;
	delete m_pInstance;
	m_pInstance = 0;
}

void KviCustomizeToolBarsDialog::display()
{
	if(m_pInstance)return;
	m_pInstance = new KviCustomizeToolBarsDialog(g_pFrame);
	m_pInstance->show();
}

void KviCustomizeToolBarsDialog::closeEvent(TQCloseEvent * e)
{
	e->ignore();
	delete this;
}

#include "toolbareditor.moc"
