//=============================================================================
//
//   File : managementdialog.cpp
//   Created on Fri 08 Apr 2005 14:54:56 by Szymon Stefanek
//
//   This file is part of the KVIrc IRC Client distribution
//   Copyright (C) 2005 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 "managementdialog.h"

#include "kvi_listview.h"
#include "kvi_locale.h"
#include "kvi_frame.h"
#include "kvi_iconmanager.h"
#include "kvi_kvs_scriptaddonmanager.h"
#include "kvi_window.h"

#include "kvi_filedialog.h"
#include "kvi_fileutils.h"
#include "kvi_kvs_script.h"
#include "kvi_sourcesdate.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 "kvi_tal_scrollview.h"
#ifdef COMPILE_USE_QT4
	#include <tq3header.h>

#else
	#include <tqheader.h>
#endif
#include "kvi_draganddrop.h"
#include <tqpainter.h>
#include <tqpixmap.h>
#include <tqmessagebox.h>
#include <tqevent.h>

KviScriptManagementDialog * KviScriptManagementDialog::m_pInstance = 0;
extern TQRect g_rectManagementDialogGeometry;


#define LVI_ICON_SIZE 32
#define LVI_BORDER 4
#define LVI_SPACING 8
#define LVI_MINIMUM_TEXT_WIDTH 300
#define LVI_MINIMUM_CELL_WIDTH (LVI_MINIMUM_TEXT_WIDTH + LVI_BORDER + LVI_ICON_SIZE + LVI_SPACING + LVI_BORDER)

KviScriptAddonListViewItem::KviScriptAddonListViewItem(KviTalListView * v,KviKvsScriptAddon * a)
: KviTalListViewItem(v,"")
{
	m_pAddon = new KviKvsScriptAddon(*a);
	m_pListView = v;
	TQString t = "<nobr><b>";
	t += a->visibleName();
	t += "</b> [";
	t += a->version();
	t += "]";
	t += " <font color=\"#a0a0a0\">[";
	t += a->name();
	t += "]</font></nobr>";
	t += "<br><nobr><font size=\"-1\">";
	t += a->description();
	t += "</font></nobr>";
	m_szKey = a->visibleName().upper();
#ifdef COMPILE_USE_QT4
	m_pText = new TQTextDocument();
	m_pText->setHtml(t);
	m_pText->setDefaultFont(v->font());
#else
	m_pText = new TQSimpleRichText(t,v->font());
#endif

	TQPixmap * p = a->icon();
	m_pIcon = p ? new TQPixmap(*p) : new TQPixmap(LVI_ICON_SIZE,LVI_ICON_SIZE);
}

KviScriptAddonListViewItem::~KviScriptAddonListViewItem()
{
	delete m_pIcon;
	delete m_pText;
	delete m_pAddon;
}

TQString KviScriptAddonListViewItem::key(int,bool) const
{
	return m_szKey;
}

void KviScriptAddonListViewItem::setup()
{
	KviTalListViewItem::setup();
	int iWidth = m_pListView->visibleWidth();
	if(iWidth < LVI_MINIMUM_CELL_WIDTH)iWidth = LVI_MINIMUM_CELL_WIDTH;
	iWidth -= LVI_BORDER + LVI_ICON_SIZE + LVI_SPACING + LVI_BORDER;
	
	#ifdef COMPILE_USE_QT4 
	int iHeight = m_pText->size().height() + (2 * LVI_BORDER);
	#else
	m_pText->setWidth(iWidth);
	int iHeight = m_pText->height() + (2 * LVI_BORDER);
	#endif
	if(iHeight < (LVI_ICON_SIZE + (2 * LVI_BORDER)))iHeight = LVI_ICON_SIZE + (2 * LVI_BORDER);
	setHeight(iHeight+2);
}

void KviScriptAddonListViewItem::paintCell(TQPainter * p,const TQColorGroup & cg,int column,int width,int align)
{
	#ifdef COMPILE_USE_QT4
	if (isSelected())
	{
		TQColor col(m_pListView->palette().highlight());
		col.setAlpha(127);
		p->setBrush(col);
		p->drawRect(0, 0, m_pListView->visibleWidth(), height());
	}
	p->drawPixmap(LVI_BORDER,LVI_BORDER,*m_pIcon);
	int afterIcon = LVI_BORDER + LVI_ICON_SIZE + LVI_SPACING;
	int www = m_pListView->visibleWidth() - (afterIcon + LVI_BORDER);
	p->translate(afterIcon,LVI_BORDER);
	m_pText->setPageSize(TQSizeF(www,height() - (LVI_BORDER * 2)));
	m_pText->drawContents(p);
	#else
	p->drawPixmap(LVI_BORDER,LVI_BORDER,*m_pIcon);
	int afterIcon = LVI_BORDER + LVI_ICON_SIZE + LVI_SPACING;
	int www = m_pListView->visibleWidth() - (afterIcon + LVI_BORDER);
	m_pText->setWidth(www);
	if(isSelected())
	{
		TQColorGroup cg2(cg);
		cg2.setColor(TQColorGroup::HighlightedText,cg.text());
	
		m_pText->draw(p,afterIcon,LVI_BORDER,TQRect(afterIcon,LVI_BORDER,www,height() - (LVI_BORDER * 2)),cg2);
	} else {
		m_pText->draw(p,afterIcon,LVI_BORDER,TQRect(afterIcon,LVI_BORDER,www,height() - (LVI_BORDER * 2)),cg);
	}
	#endif
}







KviScriptAddonListView::KviScriptAddonListView(TQWidget * pParent)
: KviListView(pParent)
{
	TQPixmap * p = g_pIconManager->getImage("kvi_dialog_addons.png");
	if(p)setBackgroundOverlayPixmap(p,TQt::AlignRight | TQt::AlignBottom);

	setSelectionMode(Single);
	header()->hide();
	int iWidth = visibleWidth();
	if(iWidth < LVI_MINIMUM_CELL_WIDTH)iWidth = LVI_MINIMUM_CELL_WIDTH;
	addColumn("",iWidth);
	setSorting(0,true);
}

KviScriptAddonListView::~KviScriptAddonListView()
{
}

void KviScriptAddonListView::resizeEvent(TQResizeEvent * e)
{
	KviListView::resizeEvent(e);
	int iWidth = visibleWidth();
	if(iWidth < LVI_MINIMUM_CELL_WIDTH)iWidth = LVI_MINIMUM_CELL_WIDTH;
	setColumnWidth(0,iWidth);
}


KviScriptManagementDialog::KviScriptManagementDialog(TQWidget * p)
: TQDialog(p,"" /*,WType_TopLevel | WStyle_Customize | WStyle_Title | WStyle_StaysOnTop | WStyle_DialogBorder*/)
{
	setCaption(__tr2qs("Manage Script-Based Addons"));
	setIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ADDONS)));
	setModal(true);

	m_pInstance = this;

	TQGridLayout * g = new TQGridLayout(this,11,3,4,5);
	
	/*TQLabel * lb = new TQLabel(this);
	lb->setFrameStyle(TQFrame::WinPanel | TQFrame::Sunken);

	g->addMultiCellWidget(lb,0,10,0,0);
	TQPixmap * pix = g_pIconManager->getImage("kvi_dialog_addons.png");
	if(pix)
	{
		lb->setPixmap(*pix);
		lb->setFixedWidth(pix->width());
	}
	lb->setBackgroundColor(TQt::black);
	lb->setAlignment(TQt::AlignBottom | TQt::AlignRight);
	*/
	m_pListView = new KviScriptAddonListView(this);
	g->addMultiCellWidget(m_pListView,0,10,1,1);

	m_pConfigureButton = new TQPushButton(__tr2qs("Configure"),this);
	connect(m_pConfigureButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(configureScript()));
	g->addWidget(m_pConfigureButton,0,2);

	m_pHelpButton = new TQPushButton(__tr2qs("Show Help"),this);
	connect(m_pHelpButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(showScriptHelp()));
	g->addWidget(m_pHelpButton,1,2);

	g->addRowSpacing(2,40);

	m_pUninstallButton = new TQPushButton(__tr2qs("Uninstall"),this);
	connect(m_pUninstallButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(uninstallScript()));
	g->addWidget(m_pUninstallButton,3,2);

	g->addRowSpacing(4,15);

	TQFrame *f = new TQFrame(this);
	f->setFrameStyle(TQFrame::HLine | TQFrame::Sunken);
	g->addWidget(f,5,2);
	
	g->addRowSpacing(6,15);

	m_pInstallButton = new TQPushButton(__tr2qs("Install Addon..."),this);
	connect(m_pInstallButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(installScript()));
	g->addWidget(m_pInstallButton,7,2);

	m_pGetScriptsButton = new TQPushButton(__tr2qs("More Addons..."),this);
	connect(m_pGetScriptsButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(getMoreScripts()));
	g->addWidget(m_pGetScriptsButton,8,2);

	TQPushButton * b = new TQPushButton(__tr2qs("Close"),this);
	connect(b,TQT_SIGNAL(clicked()),this,TQT_SLOT(closeClicked()));
	g->addWidget(b,10,2);

	g->setRowStretch(9,1);
	g->setColStretch(1,1);

	fillListView();

	currentChanged(0);
	connect(m_pListView,TQT_SIGNAL(currentChanged(KviTalListViewItem *)),this,TQT_SLOT(currentChanged(KviTalListViewItem *)));
	//currentToolBarChanged();

	if(g_rectManagementDialogGeometry.y() < 5)
	{
		g_rectManagementDialogGeometry.setY(5);
	}
	resize(g_rectManagementDialogGeometry.width(),
		g_rectManagementDialogGeometry.height());
	move(g_rectManagementDialogGeometry.x(),
		g_rectManagementDialogGeometry.y());
}

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

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

void KviScriptManagementDialog::fillListView()
{
	m_pListView->clear();
	KviPointerHashTable<TQString,KviKvsScriptAddon> * d = KviKvsScriptAddonManager::instance()->addonDict();
	if(!d)return;
	KviPointerHashTableIterator<TQString,KviKvsScriptAddon> it(*d);
	KviScriptAddonListViewItem * item;
	while(KviKvsScriptAddon * a = it.current())
	{
		item = new KviScriptAddonListViewItem(m_pListView,a);
		++it;
	}
}

void KviScriptManagementDialog::currentChanged(KviTalListViewItem *)
{
	KviScriptAddonListViewItem * it = (KviScriptAddonListViewItem *)m_pListView->currentItem();
	if(!it)
	{
		m_pConfigureButton->setEnabled(false);
		m_pUninstallButton->setEnabled(false);
		m_pHelpButton->setEnabled(false);
	} else {
		m_pConfigureButton->setEnabled(!(it->addon()->configureCallbackCode().isEmpty()));
		m_pHelpButton->setEnabled(!(it->addon()->helpCallbackCode().isEmpty()));
		m_pUninstallButton->setEnabled(true);
	}
}

void KviScriptManagementDialog::showScriptHelp()
{
	KviScriptAddonListViewItem * it = (KviScriptAddonListViewItem *)m_pListView->currentItem();
	if(!it)return;
	if(it->addon()->helpCallbackCode().isEmpty())return;
	it->addon()->executeHelpCallback(g_pActiveWindow);
}

void KviScriptManagementDialog::configureScript()
{
	KviScriptAddonListViewItem * it = (KviScriptAddonListViewItem *)m_pListView->currentItem();
	if(!it)return;
	if(it->addon()->configureCallbackCode().isEmpty())return;
	it->addon()->executeConfigureCallback(g_pActiveWindow);
}

void KviScriptManagementDialog::uninstallScript()
{
	KviScriptAddonListViewItem * it = (KviScriptAddonListViewItem *)m_pListView->currentItem();
	if(!it)return;

	TQString txt = "<p>";
	txt += __tr2qs("Do you really want to uninstall the addon \"%1\" ?").arg(it->addon()->visibleName());
	txt += "</p>";
	
	if(TQMessageBox::question(this,
		__tr2qs("Confirm addon uninstallation"),txt,__tr2qs("&Yes"),__tr2qs("&No"),0,1) != 0)return;

	KviKvsScriptAddonManager::instance()->unregisterAddon(it->addon()->name(),g_pActiveWindow);
	
	fillListView();
	currentChanged(0);
}

void KviScriptManagementDialog::getMoreScripts()
{
	KviKvsScript::run("openurl http://www.kvirc.net/?id=addons&version=" KVI_VERSION "." KVI_SOURCES_DATE,g_pActiveWindow);
}

void KviScriptManagementDialog::installScript()
{
	TQString buffer;

	if(!KviFileDialog::askForOpenFileName(buffer,__tr2qs("Please select the addon installation file"),TQString(),"install.kvs",false,true))return;

	buffer.replace("\\","\\\\");

	TQString szCmd = "parse \"";
	szCmd += buffer;
	szCmd += "\"";

	KviKvsScript::run(szCmd,g_pActiveWindow);

	fillListView();
	currentChanged(0);

	m_pListView->publicUpdateContents();
	//m_pListView->triggerUpdate();
}

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

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

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

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

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

