/***************************************************************************
 *   Copyright (C) 2005 by Silpa & Kamesh                                  *
 *   us@avasarala                                                          *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/



#include "ktemperaturewidget.h"
#include <knuminput.h> 
#include <qtimer.h>
#include <ksystemtray.h>
#include <kurlrequester.h>
#include <kpopupmenu.h>
#include <kaboutdialog.h> 
#include <qcolor.h>
#include <qstring.h>
#include <qdir.h>
#include <qrect.h>
#include <qdesktopwidget.h>  



KTemperatureWidget::KTemperatureWidget(QWidget* parent, const char* name, WFlags fl)
        : KTemperatureWidgetBase(parent,name,fl)
{
    FILE* configFilePtr;
    QDesktopWidget desktopScreen;
    unsigned int entry;
    int thermalFileFound = FALSE;
    QRect screenRectangle = desktopScreen.screenGeometry(-1);
    QRect maxChildRect((screenRectangle.width()/3),(screenRectangle.height()/3),
    this->monitorInterfaceSelect->width() + 20,this->height());
    
    this->setGeometry(maxChildRect);
    
    if(checkAcpiThermalModule() == FALSE)
    {
       /*
          Ask for root password and load thermal
	  module
       */
       system("kdesu --caption \"Loading ACPI modules\" modprobe thermal");
    }
    if(checkAcpiThermalModule() == TRUE)
    {
       QDir acpiThermalDir("/proc/acpi/thermal_zone");
       for(entry = 0; entry < acpiThermalDir.count(); entry++)
       {
          if((acpiThermalDir[entry] == "..") || (acpiThermalDir[entry] == "."))
	  {
	     continue;
	  }
	  /*there is a third entry and that is the temperature file */
	  thermalFileFound = TRUE;
	  strcpy(monitorInterface,acpiThermalDir[entry].ascii());
	  break;
       }
    }
    sprintf(configFile,"%s%s",getenv("HOME"),"/.ktemperatue");
    configFilePtr = fopen(configFile,"r");
    if(configFilePtr == NULL)
    {
       pollIntreval = 1;
       maxSysTemperature = 70;
       if(thermalFileFound == FALSE)
       {
          strcpy(monitorInterface,"/proc/acpi/thermal_zone/THRM/temperature");
       }
    }
    else
    {
       fscanf(configFilePtr,"%d",&pollIntreval);
       pollIntrevalBox->setValue(pollIntreval);
       fscanf(configFilePtr,"%d",&maxSysTemperature);
       sysMaxTempInput->setValue(maxSysTemperature);
       fscanf(configFilePtr,"%s",monitorInterface);
       fclose(configFilePtr);
    }
    monitorInterfaceSelect->setProperty("url", monitorInterface);
    rednessStep = 120.0/(maxSysTemperature - 35.0);
    pollTimer = new QTimer( this );
    connect( pollTimer, SIGNAL(timeout()),this, SLOT(checkTemperature()));
    
    pollTimer->start( pollIntreval * 1000 );
}

KTemperatureWidget::~KTemperatureWidget()
{
   
}

/*$SPECIALIZATION$*/
void KTemperatureWidget::cancelButton_clicked()
{
    hide();
}

void KTemperatureWidget::setButton_clicked()
{
    FILE *configFilePtr;
    QString url;
    pollIntreval = pollIntrevalBox->value();
    pollTimer->stop();
    pollTimer->start( pollIntreval * 1000 );
    
    
    maxSysTemperature = sysMaxTempInput->value();
    rednessStep = 120/(maxSysTemperature - 35.0);
    
    url = monitorInterfaceSelect->url();
    strcpy(monitorInterface, url.ascii());
    
    configFilePtr = fopen(configFile,"w");
    if(configFilePtr == NULL)
    {
       return;
    }
    else
    {
       fprintf(configFilePtr,"%d %d %s",pollIntreval,maxSysTemperature,monitorInterface);
       fclose(configFilePtr);
    }
    hide();
}

#include "ktemperaturewidget.moc"
/*!
    \fn KTemperatureWidget::checkTemperature()
 */
void KTemperatureWidget::checkTemperature()
{
    /// @todo implement me
    FILE* temperatureFile;
    QColor   sysTrayColor,textColor;
    char temperatureString[32];
    int hue;
    
    temperatureFile = fopen(monitorInterface,"r");
    if(temperatureFile == NULL)
    {
       trayObject->setText("NA");
       return;
    }
    fscanf(temperatureFile,"%s",temperatureString);
    fscanf(temperatureFile,"%s",temperatureString);
    fclose(temperatureFile);
    
    hue = 120 - ((int)((atoi(temperatureString) - 35.0) * rednessStep));
    sysTrayColor.setHsv(hue,255,255);
    textColor.setHsv(255,255,255);
    trayObject->setPaletteBackgroundColor (sysTrayColor);
    trayObject->setPaletteForegroundColor(textColor);
    trayObject->repaint();
    trayObject->setText(temperatureString);
}


/*!
    \fn KTemperatureWidget::setTrayReference(KSystemTray* systemTrayObject)
 */
void KTemperatureWidget::setTrayReference(KSystemTray* systemTrayObject)
{
    /// @todo implement me
    trayObject = systemTrayObject;
}

void KTemperatureWidget::monitorInterfaceSelect_urlSelected(const QString& selectedInterface)
{
   strcpy(monitorInterface, selectedInterface.ascii());
}

/*!
    \fn KTemperatureWidget::checkAcpiThermalModule(void)
 */
int KTemperatureWidget::checkAcpiThermalModule(void)
{
    /// @todo implement me
    unsigned int entry,thermalPresent = FALSE;
    QDir acpiDir("/proc/acpi");
    QString thermalFile("thermal_zone");
    
    if(acpiDir.exists() == FALSE)
    {
       return FALSE;
    }
    
    for(entry = 0; entry < acpiDir.count(); entry++)
    {
        if(thermalFile == acpiDir[entry])
	{
	   thermalPresent = TRUE;
	   break;
	}
    }
    return thermalPresent;
}

void KTemperatureWidget::pause(void)
{
   KPopupMenu *systemTrayMenu = trayObject->contextMenu();
   
   pollTimer->stop();
   systemTrayMenu->setItemEnabled(ID_RESTART,TRUE);
   systemTrayMenu->setItemEnabled(ID_UPDATE,TRUE);
   systemTrayMenu->setItemEnabled(ID_PAUSE,FALSE);
}

void KTemperatureWidget::update(void)
{  
   checkTemperature();
}

void KTemperatureWidget::restart(void)
{
   KPopupMenu *systemTrayMenu = trayObject->contextMenu();

   pollTimer->start( pollIntreval * 1000 );
   systemTrayMenu->setItemEnabled(ID_RESTART,FALSE);
   systemTrayMenu->setItemEnabled(ID_UPDATE,FALSE);
   systemTrayMenu->setItemEnabled(ID_PAUSE,TRUE);

}

void KTemperatureWidget::about(void)
{
   KAboutDialog *aboutDialog = new KAboutDialog(KAboutDialog::AbtProduct,"About KTemperature",0,KDialogBase::NoDefault,this,QString::null,FALSE,FALSE,
   QString::null,QString::null,QString::null);
   aboutDialog->setProduct("KTemperature","1.9-1","Venkata Avasarala",__DATE__);
   aboutDialog->show();
}


/*!
    \fn KTemperatureWidget::accelaratorHandler(int)
 */
void KTemperatureWidget::accelaratorHandler(int itemId)
{
    /// @todo implement me
    printf("In handler, %X\n",itemId);
    switch(itemId)
    {
       case ID_PAUSE:
       printf("In ID_PAUSE");
       break;
       case ID_RESTART:
       break;
       case ID_UPDATE:
       break;
    }
}
