/*****************************************************************

Copyright (c) 1996-2000 the kicker authors. See file AUTHORS.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <qtimer.h>
#include <qtooltip.h>
#include <qlabel.h>
#include <qpopupmenu.h>
#include <qdatetime.h>
#include <qtimer.h>
#include <time.h>

#include <kglobal.h>
#include <kprocess.h>
#include <klocale.h>
#include <kstddirs.h>
#include <kdialog.h>
#include <kwinmodule.h>

#include "dateapplet.h"

KWinModule *kwin_module;

extern "C"
{
  InternalApplet* init(QWidget *parent, KWinModule *module)
  {
    kwin_module = module;
	KGlobal::locale()->insertCatalogue("kdateapplet");
    return new DateApplet(parent, "kdateapplet");
  }
}

class ClockLabel : public QLabel
{
public:
  ClockLabel(QWidget *parent = 0, const char *name = 0)
    : QLabel(parent, name)
  {
    rmbMenu = new QPopupMenu(this);
    rmbMenu->insertItem(i18n("Change Date/Time"));
  }
 void mousePressEvent(QMouseEvent *e)
  {
    if (e->button() == RightButton) {
      if (!KStandardDirs::findExe("kcmtime"))
        return;
      else {
        int i = rmbMenu->exec(this->mapToGlobal(QPoint(0-rmbMenu->sizeHint().width(), 0)));
        i = rmbMenu->indexOf(i);
        if (i == 0) {
          KProcess proc;
          proc << KStandardDirs::findExe("kcmtime");
          proc.start(KProcess::DontCare);
        }
      }
    }
  }
  
private:
  QPopupMenu *rmbMenu;
};

DateApplet::DateApplet(QWidget* parent, const char* name )
  : InternalApplet( parent, name )
{
  label = new ClockLabel( this );
  
  // for now, should be configurable
  clockBeats = FALSE;
  
  QTime cur_time = QTime::currentTime();
  clock_timer = 0;
  int next_minute_break = (60 - cur_time.second()) * 1000 - cur_time.msec();
  QTimer::singleShot(next_minute_break, this, SLOT(updateClock()));
}

DateApplet::~DateApplet() {}

int DateApplet::widthForHeight(int)
{
  QString longStr = longString();

  QFont tmpFont(label->font());
  tmpFont.setPointSize(10);
  label->setFont(tmpFont);

  while (label->fontMetrics().lineSpacing() +
         KDialog::marginHint() * 2 &&
         tmpFont.pointSize() >= 10) {
    tmpFont.setPointSize(tmpFont.pointSize()-1);
    if (tmpFont.exactMatch())
      label->setFont(tmpFont);
    }
 
  return label->fontMetrics().boundingRect(longStr).width() + KDialog::marginHint() * 2;
}

int DateApplet::heightForWidth(int width)
{
  QString longStr = longString();

  QFont tmpFont(label->font());
  tmpFont.setPointSize(10);
  label->setFont(tmpFont);

  while (label->fontMetrics().boundingRect(longStr).width() +
         KDialog::marginHint() * 2 > width &&
         tmpFont.pointSize() >= 8) {
    tmpFont.setPointSize(tmpFont.pointSize()-1);
    if (tmpFont.exactMatch())
      label->setFont(tmpFont);
  }

  return label->fontMetrics().lineSpacing() + KDialog::marginHint();
}

QString DateApplet::longString()
{
  // fix label_date size (PGB)
  int maxSize = 0, strWidth;
  QDateTime datetime(QDateTime::currentDateTime());
  QString longStr;
  
  for (int i = 1; i < 8; i++) {
    strWidth = label->fontMetrics().width(KGlobal::locale()->weekDayName(datetime.addDays(i).date().dayOfWeek()) + '\n');
    if (strWidth > maxSize) {
      maxSize = strWidth;
      longStr = KGlobal::locale()->weekDayName(datetime.addDays(i).date().dayOfWeek()) + '\n';
    }
  }
  
  strWidth = label->fontMetrics().width(KGlobal::locale()->formatDate(datetime.date(), true));
  if (strWidth > maxSize) {
    maxSize = strWidth;
    longStr = KGlobal::locale()->formatDate(datetime.date(), true);
  }
  
  strWidth = label->fontMetrics().width(KGlobal::locale()->formatTime(datetime.time()));
  if (strWidth > maxSize) {
    maxSize = strWidth;
    longStr = KGlobal::locale()->formatTime(datetime.time());
  }
  return longStr;
}

void DateApplet::resizeEvent( QResizeEvent* )
{
  label->setGeometry(rect());
  setLabelDate();
}

void DateApplet::setLabelDate()
{
  QDateTime datetime = QDateTime::currentDateTime();

  QString dayline;
  QString timeline;
  QString dateline;

  dayline = KGlobal::locale()->weekDayName(datetime.date().dayOfWeek());

  if (orientation() == Vertical)
    dayline.truncate(3); // only keep first three letters

  dayline += '\n';

  if (clockBeats) {
    time_t curtime = time(0);
    struct tm *loctime = gmtime(&curtime);
    long iTime = (((loctime->tm_hour*3600 +
                    loctime->tm_min*60 +
                    loctime->tm_sec)+3600)*1000)/86400;

    if( iTime >= 1000 )
      iTime -= 1000;
    else if( iTime < 0 )
      iTime += 1000;

    timeline.sprintf("@%.3d", (int)iTime );
  } else {
    timeline = KGlobal::locale()->formatTime(datetime.time());
  }

  dateline = '\n' + KGlobal::locale()->formatDate(datetime.date(), true);

  if (label->fontMetrics().lineSpacing() * 3 <= height()) {
    label->setText(QString(dayline)+timeline+dateline);
    QToolTip::remove(label);
  } else if (fontMetrics().lineSpacing() * 2 <= height()) {
    label->setText(timeline+dateline);
    QToolTip::remove(label);
  } else {
    label->setText(timeline);
    QToolTip::add(label, KGlobal::locale()->formatDate(datetime.date()));
  }
}

void DateApplet::updateClock()
{
  setLabelDate();

  if ( !clock_timer ) {
    clock_timer = new QTimer(this);
    connect(clock_timer, SIGNAL(timeout()),
            this, SLOT( updateClock() ) );
    (void) clock_timer->start(clockBeats ? 86400 : 60000);
  }
  // Adjust time interval in case system time has been adjusted
  // (i.e. ntpdate or something similiar)

  QTime cur_time = QTime::currentTime();

  if(clockBeats) {
    struct tm* loctime;
    time_t curtime = time(0);
    loctime = gmtime(&curtime);
    long next_break = 86400-((((loctime->tm_hour*3600 + loctime->tm_min*60 +
                                loctime->tm_sec)+3600)*1000)%86400);
    clock_timer->changeInterval(next_break);
  } else
    clock_timer->changeInterval((60 - cur_time.second()) * 1000 -
                                cur_time.msec());
}
