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


#ifndef MY22_THREAD_HPP
#define MY22_THREAD_HPP

#include <qthread.h>
#include <qstring.h>
#include <KConfig>
#include <kstandarddirs.h>
#include <string>
#include "pop.hpp"
#include "imap.hpp"

class threadu : public QThread {
    Q_OBJECT
    public:
    threadu (KConfig*);
    void run ();
    void update_config();

    private:
    KConfig *conf;
    KConfigGroup conf_gr;
    int mails;
    base_io *mail;
    std::string user, pw, server;
    int type, sleep_time;
    bool sound, sound_enabled;

    signals:
    void signal_mails (int);
};

threadu::threadu (KConfig *p) :		conf(p),
					conf_gr (conf, "general")
{
}

void threadu::run() {
    sound = sound_enabled = QVariant(conf_gr.readEntry("play_sound")).toBool();
    for (;;) {
		update_config();
		try {
			if (type == 0)
				mail = new imap (user, pw, server);
			else
				 mail = new pop3 (user, pw, server);
			mails = mail->start();
			emit signal_mails(mails);
			if(mails > 0 && sound) {
				std::string command = "aplay ";
				command += KStandardDirs::locate("sound", "new_mail.wav").toAscii().data();
				system(command.c_str());
				sound = false;
			} else if (mails == 0 && sound_enabled)
				sound = true;
				delete mail;
				sleep(sleep_time*60);
		}
		catch (const std::runtime_error &e) {
			emit signal_mails(-1);
			sleep(15);
		}
    }
}

void threadu::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();
    sound_enabled = QVariant(conf_gr.readEntry("play_sound")).toBool();
}

#endif
