/***************************************************************************
                          kweather.cpp  -  description
                             -------------------
    begin                : Wed Jul  5 23:09:02 CDT 2000
    copyright            : (C) 2000-2003 by Ian Reinhart Geiser
                         : (C) 2002-2003 Nadeem Hasan <nhasan@kde.org>
    email                : geiseri@msoe.edu
 ***************************************************************************/

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

#include "kweather.h"
#include "reportview.h"
#include "dockwidget.h"
#include "kweatheradaptor.h"
#include "serviceinterface.h"

#include <kaboutapplicationdialog.h>
#include <kcmultidialog.h>
#include <kdebug.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kmenu.h>
#include <kconfig.h>
#include <ksettings/dialog.h>
#include <ksettings/dispatcher.h>
#include <kaboutdata.h>
#include <ktoolinvocation.h>

#include <QtCore/QFile>
#include <QtCore/QTimer>
#include <QtGui/QMouseEvent>
#include <QtCore/QTextStream>
#include <QtGui/QResizeEvent>

extern "C"
{
    KDE_EXPORT K3PanelApplet* init(QWidget *parent, const QString& configFile)
    {
        KGlobal::locale()->insertCatalog("kweather");
        kweather *theApplet = new kweather(configFile, K3PanelApplet::Normal, 0, parent);
        return theApplet;
    }
}

kweather::kweather(const QString& configFile, K3PanelApplet::Type t, int actions,
        QWidget *parent) :
        K3PanelApplet(configFile, t, actions, parent),
        mFirstRun( false ), mReport( 0 ),
        mContextMenu( 0 ), mWeatherService( 0 ), settingsDialog( 0 ), mTextColor(Qt::black)
{
        (void) new KweatherAdaptor(this );
	QDBusConnection::sessionBus().registerObject("/KWeather", this);

	kDebug(12004) << "Constructor ";

	loadPrefs();
	initContextMenu();
	initDBUS();

	dockWidget = new dockwidget(reportLocation, this );
        dockWidget->setObjectName("dockwidget");
	connect(dockWidget, SIGNAL(buttonClicked()), SLOT(doReport()));
	dockWidget->setViewMode(mViewMode);
	dockWidget->setPaletteForegroundColor(mTextColor);

	timeOut = new QTimer(this, "timeOut" );
	connect(timeOut, SIGNAL(timeout()), SLOT(timeout()));
	timeOut->start(10*60*1000);

	if(mFirstRun)
		preferences();
	else
		timeout();
}

kweather::~kweather()
{
}

void kweather::initContextMenu()
{
    mContextMenu = new KMenu(this);
    mContextMenu->addTitle(i18n("KWeather - %1", reportLocation )/*, -1, 0*/);
    mContextMenu->insertItem(SmallIcon("zoom-original"), i18n("Show &Report"),
        this, SLOT(doReport()), 0, -1, 1);
    mContextMenu->insertItem(SmallIcon("view-refresh"), i18n("&Update Now"),
        this, SLOT(slotUpdateNow()), 0, -1, 2);
    mContextMenu->insertSeparator();
    mContextMenu->insertItem(SmallIcon("kweather"), i18n("&About KWeather"), this, SLOT(about()));
    mContextMenu->insertItem(SmallIcon("configure"),
        i18n("&Configure KWeather..."), this, SLOT(preferences()));
    setCustomMenu(mContextMenu);
}

void kweather::initDBUS()
{

	if(!attach())
		return;

	kDebug(12004) << "attached to the server...";

	delete mWeatherService;
	mWeatherService = new OrgKdeKweatherServiceInterface( "org.kde.KWeatherService", "/Service", QDBusConnection::sessionBus() );
	if(!connect( mWeatherService, SIGNAL(fileUpdate(QString)), this, SLOT(refresh(QString))))
	   kDebug(12004) << "Could not attach dbus signal...";
}


/** about box */
void kweather::about(){
    kDebug(12004) << "Telling about";
    KAboutData aboutData("KWeather", 0, ki18n("KWeather"), "2.1.0",
            ki18n("Weather applet for the Kicker"), KAboutData::License_GPL_V2);
    aboutData.addAuthor(ki18n("Ian Reinhart Geiser"), KLocalizedString(), "geiseri@kde.org",
            "http://www.kde.org/");
    //aboutData.addAuthor(ki18n("Nadeem Hasan"),  KLocalizedString(), "nhasan@nadmm.com", "http://www.nadmm.com/");
    aboutData.addCredit(ki18n("Nadeem Hasan"), ki18n("Lots of bugfixes,"
            " improvements and cleanups."), "nhasan@nadmm.com");
    aboutData.addCredit(ki18n("Will Andrews"), ki18n("Fixed for BSD port"),
            "wca@users.sourceforge.net");
    aboutData.addCredit(ki18n("Ben Burton"), ki18n("Debian fixes"), "benb@acm.org");
    aboutData.addCredit(ki18n("Otto Bruggeman"), ki18n("Fixed the i18n stuff and"
            " made sure the indentation was consistent :P"), "bruggie@home.nl");
    aboutData.addCredit( ki18n("Carles Carbonell Bernado"),
            ki18n( "Great new weather icons" ), "mail@carlitus.net" );
    aboutData.addCredit( ki18n("John Ratke"),
            ki18n( "Improvements and more code cleanups" ), "jratke@comcast.net" );

    KAboutApplicationDialog about(&aboutData, this);
    about.setIcon( KIconLoader::global()->iconPath( "kweather", -KIconLoader::SizeLarge ) );
    about.exec();
}

/** prefs */
void kweather::preferences()
{
    kDebug(12004) << "prefs";

    savePrefs();

    if ( settingsDialog == 0 )
    {
      settingsDialog = new KCMultiDialog( this );
      connect( settingsDialog, SIGNAL( configCommitted() ), SLOT( slotPrefsAccepted() ) );

      settingsDialog->addModule( "kcmweather.desktop" );
      settingsDialog->addModule( "kcmweatherservice.desktop" );
    }

    settingsDialog->show();
    settingsDialog->raise();
}

/** The help handler */
void kweather::help()
{
    KToolInvocation::invokeHelp(QString(), QLatin1String("kweather"));
}

/** Display the current weather report. */
void kweather::doReport()
{
    if ( reportLocation.isEmpty() )
    {
        // no station to display defined -> open settings dialog
        preferences();
        return;
    }

	kDebug(12004) << "Showing out the report";
	if ( mReport == 0 )
	{
		mReport = new reportView(reportLocation);

		connect( mReport, SIGNAL( finished() ), SLOT( slotReportFinished() ) );
	}

	mReport->show();
	mReport->raise();
}

void kweather::slotReportFinished(){
	mReport->delayedDestruct();
	mReport = 0;
}

/** load the application */
void kweather::loadPrefs(){
    kDebug(12004) << "Loading Prefs";
    KConfig *kcConfig = config();
    kcConfig->reparseConfiguration();

    if (!kcConfig->hasGroup ("General Options") )
        mFirstRun = true;

    KConfigGroup group = kcConfig->group("General Options");
    logOn = group.readEntry("logging", false);
    fileName = group.readPathEntry("log_file_name", QString());
    reportLocation = group.readEntry("report_location");
    mViewMode = group.readEntry("smallview_mode", int(dockwidget::ShowAll));
    mTextColor = group.readEntry("textColor", QColor(Qt::black));
}

/** Save the application mPrefs. */
void kweather::savePrefs(){
	kDebug(12004) << "Saving Prefs...";
	KConfigGroup group = config()->group("General Options");
	group.writeEntry("logging", logOn);
	group.writeEntry("report_location", reportLocation);
	group.writeEntry("smallview_mode", mViewMode);
	group.writePathEntry("log_file_name", fileName );
	group.sync();
}

void kweather::showWeather()
{
    kDebug(12004) << "Show weather";
    dockWidget->showWeather();
    emit updateLayout();
}

void kweather::writeLogEntry()
{
    // Write data line in the CSV format
    if (logOn && !fileName.isEmpty())
    {
        kDebug(12004)<< "Try log file:" << fileName;
        QFile logFile(fileName);
        QTextStream logFileStream(&logFile);
        if (logFile.open(QIODevice::Append | QIODevice::ReadWrite))
        {
            QString temperature = mWeatherService->temperature(reportLocation );
            QString wind        = mWeatherService->wind(reportLocation );
            QString pressure    = mWeatherService->pressure(reportLocation );
            QString date        = mWeatherService->date(reportLocation );
            QStringList weather = mWeatherService->weather(reportLocation );
            QStringList cover   = mWeatherService->cover(reportLocation );
            QString visibility  = mWeatherService->visibility(reportLocation );
            logFileStream << date << ",";
            logFileStream << wind << ",";
            logFileStream << temperature << ",";
            logFileStream << pressure << ",";
            logFileStream << cover.join(";") << ",";
            logFileStream << visibility << ",";
            logFileStream << weather.join(";");
            logFileStream << endl;
        }
        else
        {
            KMessageBox::sorry( this,
                    i18n("For some reason the log file could not be written to.\n"
                    "Please check to see if your disk is full or if you "
                    "have write access to the location you are trying to "
                    "write to."),
                    i18n("KWeather Error"));
        }
        logFile.close();
    }
}

/** get new data */
void kweather::timeout(){

	if ( !mWeatherService )
		initDBUS();

	if ( mWeatherService )
	{
		// isEmtpy is true for null and 0 length strings
		if ( !reportLocation.isEmpty() )
		{
			kDebug(12004)<< "Requesting new data for " << reportLocation;
			mWeatherService->update(reportLocation);
		}
	}
}

int kweather::widthForHeight(int h) const
{
	//kDebug(12004) << "widthForHeight " << h;
	dockWidget->setOrientation(Qt::Horizontal);
	int w = dockWidget->widthForHeight(h);
	return w;
}

int kweather::heightForWidth(int w) const
{
	kDebug(12004) << "heightForWidth " << w;
	dockWidget->setOrientation(Qt::Vertical);
	int h = dockWidget->heightForWidth( w );
	return h;
}

void kweather::refresh(const QString &stationID)
{
	kDebug(12004) << "refresh " << stationID;
	if( stationID == reportLocation)
	{
		showWeather();
		writeLogEntry();
	}
}

void kweather::slotPrefsAccepted()
{
    // Preferences have been saved in the config file by the KCModule,
    // so read them out.
    loadPrefs();

    dockWidget->setLocationCode(reportLocation);
    dockWidget->setViewMode(mViewMode);
    dockWidget->setPaletteForegroundColor(mTextColor);
    emit updateLayout();

    if (logOn && !fileName.isEmpty())
    {
        QFile logFile(fileName);
        // Open the file, create it if not already exists
        if (logFile.open(QIODevice::ReadWrite))
        {
            if (logFile.size() == 0)
            {
                // Empty file, put the header
                QTextStream logFileStream(&logFile);
                logFileStream << "Date,Wind Speed & Direction,Temperature,Pressure,Cover,Visibility,Current Weather" << endl;
            }
            logFile.close();
        }
        else
        {
            kDebug(12004) << "There was an error opening the file....";
            KMessageBox::sorry( this,
                    i18n("For some reason a new log file could not be opened.\n"
                    "Please check to see if your disk is full or if you have "
                    "write access to the location you are trying to write to."),
                    i18n("KWeather Error"));
        }
    }

    timeout();
}

void kweather::mousePressEvent(QMouseEvent *e)
{
    if ( e->button() != Qt::RightButton )
    {
        K3PanelApplet::mousePressEvent( e );
        return;
    }

    mContextMenu->exec(e->globalPos());
}

void kweather::slotUpdateNow()
{
    mWeatherService->forceUpdate(reportLocation );
}

bool kweather::attach()
{
    QString error;
    kDebug(12004) << "Looking for dbus service...";
    if(!QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.KWeatherService"))
    {
        kDebug(12004) << "Could not find service so I am starting it..."
            << endl;
        if (!KToolInvocation::startServiceByDesktopName("kweatherservice",
            QStringList(), &error))
        {
            kDebug(12004) << "Starting KWeatherService failed with message: "
                << error << endl;
            return false;
        }

        kDebug (12004) << "Service Started...";
    }
    else
    {
        kDebug(12004) << "Found weather service...";
    }

    return true;
}

void kweather::resizeEvent(QResizeEvent *e)
{
	kDebug(12004) << "KWeather Resize event " << e->size();
	dockWidget->resizeView(e->size());
}

#include "kweather.moc"
