/*
 *      account_checker.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 "account_checker.hpp"

account_checker::account_checker (KConfig *p) :	conf(p),
												conf_gr (conf, "general"),
												mail(0),
												sleep_time(1)
{
}

account_checker::~account_checker () {
	if (mail)
		delete mail;
}

void account_checker::start() {
	check();
	sleep_timer.start(sleep_time*60000, this);
}

void account_checker::timerEvent(QTimerEvent *event) {
	if (event->timerId() == sleep_timer.timerId())
		check();
}

void account_checker::check() {
	update_config();
	try {
		if (type == 0)
			mail = new imap (user, pw, server, ssl);
		else
			mail = new pop3 (user, pw, server, ssl);
		mails = mail->start();
		if (headers)
			header = mail->split_headers();

		emit signal_mails(mails, header);

		delete mail;
		mail=0;
	}
	catch (const std::runtime_error &e) {
		emit signal_mails(-1);
	}
}

void account_checker::update_config() {
    user = conf_gr.readEntry("user", QString()).toAscii().data();
    pw = conf_gr.readEntry("pw", QString()).toAscii().data();
    server = conf_gr.readEntry("server", QString()).toAscii().data();
    type = conf_gr.readEntry("type", QString()) == "IMAP" ? 0 : 1;
    sleep_time = conf_gr.readEntry("time", QString()).toInt();
	ssl = QVariant(conf_gr.readEntry("ssl")).toBool();
	headers = QVariant(conf_gr.readEntry("headers")).toBool();
	sleep_time = sleep_time > 0 ? sleep_time : 1;
}
