/*
 *      plasmoid.cpp
 *
 *      Copyright 2009 Sebastian Wankerl <far_away@online.de>
 *
 *      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 option) 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 "plasmoid.hpp"
#include <QPainter>
#include <QFontMetrics>
#include <QSizeF>

#include <KConfigDialog>
#include <KDE/KNotifyConfigWidget>
#include <klocalizedstring.h>
#include <QProcess>


MailWidget1::MailWidget1(QObject *parent, const QVariantList &args):    Plasma::Applet(parent, args),
																		general_group(&conf, "general"),
                                                                        icon(this),
																		icon_new(this),
																		error_icon(this),
                                                                        mails(0),
																		need_notify(true)
{
	icon.setImagePath("widgets/no_mail");
	icon_new.setImagePath("widgets/new_mail_img");
	error_icon.setImagePath("widgets/mail_error");
	resize(150, 150);
    setHasConfigurationInterface(true);
}


MailWidget1::~MailWidget1() {
	delete thrd;
}

void MailWidget1::init() {
	Plasma::ToolTipManager::self()->registerWidget(this);
	thrd = new account_checker (&conf);
	QObject::connect(thrd, SIGNAL( signal_mails(int, std::string) ), this, SLOT( update_plasmoid(int, std::string) ) );
    thrd->start();
}

void MailWidget1::createConfigurationInterface(KConfigDialog *parent) {
    QWidget *conf_widget = new QWidget;
    my_ui.setupUi(conf_widget);

    my_ui.lineEdit->insert(general_group.readEntry("user", QString()));
    my_ui.lineEdit_2->insert(general_group.readEntry("pw", QString()));
    my_ui.lineEdit_3->insert(general_group.readEntry("server", QString()));
	my_ui.lineEdit_4->insert(general_group.readEntry("programm", QString()));
    QString temp = general_group.readEntry("type", QString());
    my_ui.comboBox->setCurrentIndex(temp == "IMAP" ? 0 : 1);
    my_ui.spinBox->setValue(QVariant(general_group.readEntry("time")).toInt());
	my_ui.checkBox->setChecked(QVariant(general_group.readEntry("ssl")).toBool());
	my_ui.checkBox_2->setChecked(QVariant(general_group.readEntry("headers")).toBool());

    connect(parent, SIGNAL(okClicked()), this, SLOT(changeConfig()));
    parent->addPage(conf_widget, i18n("Settings"), "example");

	KNotifyConfigWidget *notifyWidget = new KNotifyConfigWidget(parent);
    notifyWidget->setApplication("mail_plasmoid", QString::null, QString::null);
    KPageWidgetItem *notifyPage = parent->addPage(notifyWidget, i18n("Notifications"), "Notifications");
    notifyPage->setIcon(KIcon("preferences-desktop-notification"));
	connect(parent, SIGNAL(okClicked()), notifyWidget, SLOT(save()));
}

void MailWidget1::paintInterface (QPainter *p, const QStyleOptionGraphicsItem *option, const QRect &contentsRect) {
    Plasma::Svg *draw_icon;
	QString message = generate_mail_string();

    if (mails >= 0)
      draw_icon = mails > 0 ? &icon_new : &icon;
    else
      draw_icon = &error_icon;

    p->setRenderHint(QPainter::SmoothPixmapTransform);
    p->setRenderHint(QPainter::Antialiasing);

	QFont font = p->font();

	QSize size_main = draw_icon->size();

	if (contentsRect.height() > 120) {
		size_main.scale(contentsRect.width(), contentsRect.height(), Qt::IgnoreAspectRatio);
    	draw_icon->resize(size_main);
		draw_icon->paint(p, 0, 0);
		p->save();
		font.setBold(true);
		p->setFont(font);
		p->setPen(Qt::black);
    	p->drawText(contentsRect, Qt::AlignBottom | Qt::AlignHCenter, message);
	}
	else {
		size_main.scale(contentsRect.height(), contentsRect.height(), Qt::KeepAspectRatioByExpanding);
    	draw_icon->resize(size_main);
		draw_icon->paint(p, 0, 0);
		p->save();
		font.setPixelSize(contentsRect.height() / 2);
		p->setFont(font);
		p->setPen(Qt::red);
		p->drawText(contentsRect, Qt::AlignVCenter | Qt::AlignHCenter, QString::number(mails));
	}
    p->restore();
}

void MailWidget1::update_plasmoid (int i, std::string header) {
	mails = i;
	tm_header = QString("<b>") + generate_mail_string() + "</b><tr><tr>" + QString(header.c_str());
	QString programm = general_group.readEntry("programm", QString());

	if (i > 0 && need_notify) {
		notify=new KNotification("newMessage");
		notify->setComponentData(KComponentData("mail_plasmoid", "mail_plasmoid", KComponentData::RegisterAsMainComponent));
		notify->setText(tm_header);
		if (programm.isEmpty() == false) {
			notify->setActions(QStringList(QString("Launch ") + programm));
			connect(notify, SIGNAL(activated(unsigned int)), this , SLOT(launch_mailreader()));
		}
		notify->setFlags(KNotification::Persistent);
		notify->sendEvent();
		need_notify = false;
	}
	else if (i == 0)
		need_notify = true;

    update();
}

void MailWidget1::changeConfig() {
    general_group.writeEntry("user", my_ui.lineEdit->text());
    general_group.writeEntry("pw", my_ui.lineEdit_2->text());
    general_group.writeEntry("server", my_ui.lineEdit_3->text());
    general_group.writeEntry("type", my_ui.comboBox->currentText());
    general_group.writeEntry("time", my_ui.spinBox->value());
	general_group.writeEntry("programm", my_ui.lineEdit_4->text());
	general_group.writeEntry("ssl", my_ui.checkBox->isChecked());
	general_group.writeEntry("headers", my_ui.checkBox_2->isChecked());
}

QString MailWidget1::generate_mail_string() {
	if (mails != -1) {
		QString message = QString::number(mails);
		message += mails != 1 ? " new mails" : " new mail";
		return message;
	}
	else
		return QString("ERROR");
}

void MailWidget1::launch_mailreader() {
	QString prg = general_group.readEntry("programm", QString());
	QProcess *mail_programm = new QProcess(this);
    mail_programm->start(prg);
}

void MailWidget1::constraintsEvent(Plasma::Constraints)
{
	setBackgroundHints(NoBackground);
}

void MailWidget1::toolTipAboutToShow() {
	Plasma::ToolTipContent data;
	data.setAutohide(false);
	data.setMainText(tm_header);

	Plasma::ToolTipManager::self()->setContent(this, data);
}

void MailWidget1::toolTipHidden() {
	Plasma::ToolTipManager::self()->clearContent(this);
}

#include "plasmoid.moc"
#include "account_checker.moc"
