/*
 *  Copyright (C) 2007-2008 CMM Sigma Andrzej Chmielowiec <cmmsigma@cmmsigma.eu>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 3
 *  as published by the Free Software Foundation.
 *
 *  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.
 */

#include "MainWindow.h"
#include "AdminOptionsDialog.h"
#include "SendMailDialog.h"
#include "AboutBox.h"

static const QString welcomeString = QObject::tr(
	"<center><h2>sToken Admin v1.2</h2></center>"
);

MainWindow *MainWindow::mainWnd = 0;

extern QString lang;

MainWindow::MainWindow(QMainWindow *parent): QMainWindow(parent)
{
	mainWnd = this;

	mConfDirPath = QDir::homePath() + QDir::separator() + ".stoken_admin";
	mXmlConfFileName = QString("xml_conf");
	
	readXmlConfig();
	
	mFontName = QString("Helvetica");
	mFontSize = 10;
	setFont(QFont(mFontName, mFontSize));
	
	mModel = new TreeModel(this);
	
	connect(mModel, SIGNAL(pageActivated(QWidget*)), this, 
		SLOT(setActivePage(QWidget*)));
	connect(mModel, SIGNAL(pageDeleted(QWidget*)), this, 
		SLOT(deletePage(QWidget*)));
	
	mView = new QTreeView(this);
	mView->setModel(mModel);
	
	connect(mView, SIGNAL(clicked(const QModelIndex&)), mModel, 
		SLOT(setActive(const QModelIndex&)));
	
	refresh();
	
	createActions();
	createMenus();
	createToolBars();
	createAboutBox();
	
	mSplitter = new QSplitter;
	mPages = new QStackedWidget;
	
	QGridLayout *grid = new QGridLayout;
	mMainPage = new QWidget();
	mMainPage->setLayout(grid);
	mPages->addWidget(mMainPage);
	
	QLabel *label = new QLabel();
	label->setPixmap(QPixmap(QString(":img/stoken_logo_120_60.png")));
	label->setAlignment(Qt::AlignRight);
	grid->addWidget(label, 0, 0);
	grid->addWidget(new QLabel(welcomeString, this), 1, 0);
	grid->setRowStretch(1, 1);
	grid->setRowStretch(2, 1);
	
	mSplitter->addWidget(mView);
	mSplitter->addWidget(mPages);
	
	QList<int> sizes;
	sizes.append(200);
	sizes.append(600);
	mSplitter->setSizes(sizes);
	mSplitter->setStretchFactor(1, 1);
	
	setCentralWidget(mSplitter);
	
	setWindowIcon(QIcon(QString(":img/stoken_admin_032.png")));
	setWindowTitle(tr("sToken Admin"));
	
	resize(750, 600);
}

AdminOptions*
MainWindow::getConfig()
{
	return &config;
}

void
MainWindow::sendRequest(const QString &fileName, const QString &mail)
{
	if(!config.mailConfig.checkOutgoingConfig())
	{
		QMessageBox::information(this, tr("Information"), tr("Cannot send "
			"request. Please configure e-mail account first."));
		
		return;
	}
	
	SendMailDialog dlg(this);
	QtSmtp *smtp = dlg.getSmtp();
	
	smtp->beginNewMail();
	smtp->setServer(config.mailConfig.mSmtpServer);
	smtp->setSender(config.mailConfig.mMail, config.mailConfig.mUser);
	
	smtp->addRecipient(mail);
	smtp->setMessage(tr("This message contains request."));
	smtp->setSubject(tr("Request"));
	
	if(config.mailConfig.mOutgoingAuth)
	{
		if(config.mailConfig.mUseIncomming)
			smtp->setUserPassword(config.mailConfig.mPop3User , config.mailConfig.mPop3Pass);
		else
			smtp->setUserPassword(config.mailConfig.mSmtpUser , config.mailConfig.mSmtpPass);
	}
	
	smtp->addFileAttachment(fileName);
	
	smtp->sendMail();
	dlg.exec();
	
	QFile::remove(fileName);
}

void
MainWindow::setActivePage(QWidget *page)
{
	mPages->removeWidget(mPages->currentWidget());
	mPages->addWidget(page);
}

void
MainWindow::deletePage(QWidget *page)
{
	if (mPages->currentWidget() == page)
		setActivePage(mMainPage);
}

void
MainWindow::settings()
{
	AdminOptionsDialog *dialog = new AdminOptionsDialog(this);
	dialog->setFont(QFont(mFontName, mFontSize));
	dialog->setWindowTitle(QObject::tr("Settings"));
	
	readXmlConfig();
	dialog->setData(config);
	
	if (dialog->exec() == QDialog::Accepted)
	{
		dialog->getData(config);
		writeXmlConfig();
	}
}

void
MainWindow::incFontSize()
{
	if (mFontSize < 24)
	{
		setFont(QFont(mFontName, ++mFontSize));
		mDecFontSizeAct->setEnabled(true);
		
		if (mFontSize == 24)
			mIncFontSizeAct->setEnabled(false);
	}
}

void
MainWindow::decFontSize()
{
	if (8 < mFontSize)
	{
		mIncFontSizeAct->setEnabled(true);
		setFont(QFont(mFontName, --mFontSize));
		
		if (mFontSize == 8)
			mDecFontSizeAct->setEnabled(false);
	}
}

void
MainWindow::showPop()
{
	mModel->execContextMenu(mView->currentIndex());
}


void
MainWindow::helpSlot()
{
	mAboutBox->setActiveHelp();
	mAboutBox->exec();
}

void
MainWindow::aboutSlot()
{
	mAboutBox->setActiveAbout();
	mAboutBox->exec();
}

void
MainWindow::refresh()
{
	mModel->refresh();
	mView->setIconSize(QSize(16,16));
	mView->setIconSize(QSize(24,24));
	mView->repaint();
}

void
MainWindow::langEnSlot()
{
	lang = "";
	langExclamation();
}

void
MainWindow::langPlSlot()
{
	lang = "pl";
	langExclamation();
}

bool
MainWindow::writeXmlConfig()
{
	QFile file(mConfDirPath + QDir::separator() + mXmlConfFileName);
	if(file.open(QIODevice::WriteOnly))
	{
		config.serialize(file);
		file.close();
	}
	return true;
}

bool
MainWindow::readXmlConfig()
{
	QFile file(mConfDirPath + QDir::separator() + mXmlConfFileName);
	if(file.open(QIODevice::ReadOnly))
	{
		config.deserialize(file);
		file.close();
	}
	return true;
}

void
MainWindow::langExclamation()
{
	QMessageBox::information(this, tr("Information"), tr("Application language was "
		"changed. Please restart application to apply changes."));
}

void
MainWindow::createActions()
{
	mLang = new QActionGroup(this);
	mLangEn = new QAction(tr("English"), this);
	mLangEn->setCheckable(true);
	connect(mLangEn, SIGNAL(triggered()), this, SLOT(langEnSlot()));
	mLangPl = new QAction(tr("Polish"), this);
	mLangPl->setCheckable(true);
	connect(mLangPl, SIGNAL(triggered()), this, SLOT(langPlSlot()));
	
	mLang->addAction(mLangEn);
	mLang->addAction(mLangPl);
	
	mExitAct = new QAction(QIcon(QString(":img/exit.png")), tr("Exit"), this);
	mExitAct->setShortcut(tr("Ctrl+Q"));
	connect(mExitAct, SIGNAL(triggered()), this, SLOT(close()));
	
	mSettingsAct = new QAction(QIcon(QString(":img/configure.png")), tr("Settings"), this);
	connect(mSettingsAct, SIGNAL(triggered()), this, SLOT(settings()));
	mSettingsAct->setShortcut(tr("F11"));
	
	mRefreshAct = new QAction(QIcon(QString(":img/refresh.png")), tr("Refresh"), this);
	mRefreshAct->setShortcut(tr("F5"));
	connect(mRefreshAct, SIGNAL(triggered()), this, SLOT(refresh()));
	
	mIncFontSizeAct = new QAction(QIcon(QString(":img/view_plus.png")), tr("Increase font size"), this);
	mIncFontSizeAct->setShortcut(tr("Ctrl++"));
	connect(mIncFontSizeAct, SIGNAL(triggered()), this, SLOT(incFontSize()));
	
	mDecFontSizeAct = new QAction(QIcon(QString(":img/view_minus.png")), tr("Decrease font size"), this);
	mDecFontSizeAct->setShortcut(tr("Ctrl+-"));
	connect(mDecFontSizeAct, SIGNAL(triggered()), this, SLOT(decFontSize()));
	
	mHelpAct = new QAction(QIcon(QString(":img/contents_ii.png")), tr("Manual"), this);
	mHelpAct->setShortcut(tr("Ctrl+H"));
	connect(mHelpAct, SIGNAL(triggered()), this, SLOT(helpSlot()));
	
	mAboutAct = new QAction(QIcon(QString(":img/info.png")), tr("About"), this);
	connect(mAboutAct, SIGNAL(triggered()), this, SLOT(aboutSlot()));
}

void
MainWindow::createMenus()
{
	QMenu *language;
	mGeneralMenu = menuBar()->addMenu(tr("General"));

	language = mGeneralMenu->addMenu(tr("&Language"));
	language->addAction(mLangEn);
	language->addAction(mLangPl);
	if(lang == "pl")
		mLangPl->setChecked(true);
	else
		mLangEn->setChecked(true);

	mGeneralMenu->addSeparator();
	
	mGeneralMenu->addAction(mExitAct);
	
	mGeneralMenu = menuBar()->addMenu(tr("Settings"));
	mGeneralMenu->addAction(mSettingsAct);
	
	mViewMenu = menuBar()->addMenu(tr("View"));
	mViewMenu->addAction(mRefreshAct);
	mViewMenu->addSeparator();
	mViewMenu->addAction(mIncFontSizeAct);
	mViewMenu->addAction(mDecFontSizeAct);
	
	mHelpMenu = menuBar()->addMenu(tr("Help"));
	mHelpMenu->addAction(mHelpAct);
	mHelpMenu->addSeparator();
	mHelpMenu->addAction(mAboutAct);
}

void
MainWindow::createToolBars()
{
	mViewToolBar = addToolBar(tr("View"));
	mViewToolBar->addAction(mRefreshAct);
	mViewToolBar->addAction(mIncFontSizeAct);
	mViewToolBar->addAction(mDecFontSizeAct);
	
	mHelpToolBar = addToolBar(tr("Help"));
	mHelpToolBar->addAction(mHelpAct);
	mHelpToolBar->addAction(mAboutAct);
}

void
MainWindow::createAboutBox()
{
	mAboutBox = new AboutBox(this);
	
	// About informations.
	mAboutBox->setAboutPixmap(QPixmap(QString(":img/stoken_about_admin_384.png")));
	mAboutBox->setAboutInfo(tr("<h2>sToken Admin v1.2</h2>"
	"<br>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 3 of the License, or (at your option) any "
	"later version.<br><br>"
	"<a href=\"http://www.stoken.eu/index.en.html\">http://www.stoken.eu</a>"));
	
	// Help informations.
	mAboutBox->setHelpPixmap(QPixmap(QString(":img/stoken_about_admin_384.png")));
	mAboutBox->setHelpInfo(tr("<h2>sToken Admin v1.2</h2>"
	"<br>Online instructions to this application are avaliable on the following "
	"website: <a href=\"http://www.stoken.eu/products/man_admin/index.en.html\">"
	"http://www.stoken.eu</a>"));
	
	// License.
	QFile file(QString(":LICENSE"));
	file.open(QIODevice::ReadOnly);
	QByteArray license = file.readAll();
	file.close();
	mAboutBox->setLicense(QString(license.data()));
	
	// Thanks.
	mAboutBox->setThanksPixmap(QPixmap(QString(":img/stoken_about_admin_384.png")));
	mAboutBox->setThanksInfo(tr("<h4>Thanks to</h4>"
		"Andrzej Chmielowiec, Wiktor Kazana"
		"<h4>Special thanks</h4>"
		"Special thanks to all people who participate in development process of "
		"<a href=\"www.openssl.org\">OpenSSL</a> library and "
		"<a href=\"www.openvpn.net\">OpenVPN</a> software. Both of this projects "
		"are crucial for this application."
		));
}
