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

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 "clock.h"

#include <qtimer.h>
#include <qdatetime.h>
#include <qlayout.h>
#include <qbitmap.h>
#include <qpainter.h>
#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kapp.h>
#include <kcmdlineargs.h>
#include "kwinmodule.h"
#include <kwm.h>
#include <kpopupmenu.h>

extern "C"
{
    InternalApplet* init(QWidget *parent, KWinModule *)
    {
        return new ClockWidget(parent, "koolclockapplet");
    }
}

static const char * close_xpm[] = {
/* width height num_colors chars_per_pixel */
"16 16 3 1",
/* colors */
" 	s None	c None",
".	c white",
"X	c #707070",
/* pixels */
"                ",
"                ",
"  .X        .X  ",
"  .XX      .XX  ",
"   .XX    .XX   ",
"    .XX  .XX    ",
"     .XX.XX     ",
"      .XXX      ",
"      .XXX      ",
"     .XX.XX     ",
"    .XX  .XX    ",
"   .XX    .XX   ",
"  .XX      .XX  ",
"  .X        .X  ",
"                ",
"                "};

DatePicker::DatePicker()
    : QFrame()
{
    setCaption(i18n("Calendar"));
    setFrameStyle(QFrame::Panel | QFrame::Raised);
    setLineWidth(2);
    QGridLayout *layout = new QGridLayout(this);

    layout->addRowSpacing(0, 2);
    layout->addRowSpacing(3, 2);
    layout->addColSpacing(0, 2);
    layout->addColSpacing(3, 2);

    QToolButton *closeBtn = new QToolButton(this);
    connect(closeBtn, SIGNAL(clicked()), SLOT(close()));
    closeBtn->setIconSet(QPixmap(close_xpm));
    layout->addWidget(closeBtn, 1, 1);

    KDatePicker *picker = new KDatePicker(this);
    layout->addMultiCellWidget(picker, 1, 2, 2, 2);

    layout->setRowStretch(2, 1);
    layout->activate();
    resize(sizeHint());
    setMinimumSize(sizeHint());

    QBitmap mask(size());
    mask.fill(Qt::color1);
    QPainter p;
    p.begin(&mask);
    closeBtn->resize(closeBtn->sizeHint());
    p.fillRect(2, closeBtn->y()+closeBtn->height(), closeBtn->width()-2,
               height()-closeBtn->height()-6, Qt::color0);
    p.end();
    setMask(mask);
}

void DatePicker::closeEvent(QCloseEvent *)
{
    warning("In DatePicker close event");
    delete this;
}

Clock::Clock(QWidget *parent, const char *name)
    : QLCDNumber(parent, name)
{
    setFrameStyle(Panel | Sunken);

    KConfig *config = KGlobal::config();
    config->setGroup("koolclock");
    QString tmpStr = config->readEntry("Style", "Flat");
    if(tmpStr == "Flat")
        setSegmentStyle(QLCDNumber::Flat);
    else if(tmpStr == "Filled")
        setSegmentStyle(QLCDNumber::Filled);
    else
        setSegmentStyle(QLCDNumber::Outline);
    blink = config->readBoolEntry("Blink", false);
    ampm = config->readBoolEntry("AmPm", KGlobal::locale()->use12Clock());
    QColorGroup cg = colorGroup();
    QColor color = config->readColorEntry("LCDForeground", &Qt::green);
    cg.setColor(QColorGroup::Foreground, color);
    color = config->readColorEntry("LCDBackground", &Qt::black);
    cg.setColor(QColorGroup::Background, color);
    setPalette(QPalette(cg, cg, cg));

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(slotTimer()));
    slotTimer();
    timer->start(1000);
}

void Clock::slotTimer()
{
    static bool colon = true;
    QString newStr;
    int h = QTime::currentTime().hour();
    if(ampm) {
      if(h > 12)
        h -= 12;
      else if(h == 0)
        h = 12;
    }

    if(colon)
        newStr.sprintf("%02d:%02d", h, QTime::currentTime().minute());
    else
        newStr.sprintf("%02d %02d", h, QTime::currentTime().minute());

    if(newStr != timeStr){
        timeStr = newStr;
        display(timeStr);
    }
    if(blink)
        colon = !colon;
}

void Clock::mousePressEvent(QMouseEvent *ev)
{
    if(ev->button() == QMouseEvent::LeftButton)
        emit datePicker();
    if(ev->button() == QMouseEvent::RightButton)
       emit contextMenu();
}

Date::Date(QWidget *parent, const char *name)
    : QLabel(parent, name)
{
    setAlignment(AlignCenter);
    QFont newFont(font());
    newFont.setPointSize(10);
    newFont.setItalic(true);
    setFont(newFont);
    timer = new QTimer(this);

    connect(timer, SIGNAL(timeout()), this, SLOT(slotTimer()));
    slotTimer();
    timer->start(600000);
}

void Date::slotTimer()
{
    QString newStr = KGlobal::locale()->formatDate(QDate::currentDate(), true);
    if(newStr != dateStr){
        dateStr = newStr;
        setText(dateStr);
    }
}

void Date::mousePressEvent(QMouseEvent *ev)
{
    if(ev->button() == QMouseEvent::LeftButton)
        emit datePicker();
    if(ev->button() == QMouseEvent::RightButton)
       emit contextMenu();
}


ClockWidget::ClockWidget(QWidget *parent, const char *name)
    : InternalApplet(parent, name)
{
    cal = 0L;
    layout = new QVBoxLayout(this, 2);
    Clock* dclock;
    AnalogClock* aclock;
    
    KConfig *config = KGlobal::config();
    config->setGroup("koolclock");
    type = config->readEntry("Type", "Digital");
    if( type == "Digital" )
    {
       dclock = new Clock(this);
       connect(dclock, SIGNAL(datePicker()), SLOT(slotDatePicker()));
       connect(dclock, SIGNAL(contextMenu()), SLOT(slotContextMenu()));
       clock = dclock;
    }
    else
    {
       aclock = new AnalogClock(this);
       connect(aclock, SIGNAL(datePicker()), SLOT(slotDatePicker()));
       connect(aclock, SIGNAL(contextMenu()), SLOT(slotContextMenu()));
       clock = aclock;
    }
    date = new Date(this);
    connect(date, SIGNAL(contextMenu()), SLOT(slotContextMenu()));
    connect(date, SIGNAL(datePicker()), SLOT(slotDatePicker()));
}

int ClockWidget::widthForHeight(int h)
{
  int cw = clock->width();
  int dw = date->width();

  if(h < 32)
    return cw + dw;
  else
    return cw > dw ? cw : dw;
}

int ClockWidget::heightForWidth(int)
{
  return clock->height() + date->height();
}

void ClockWidget::resizeEvent(QResizeEvent*)
{
   relayout();
}

void ClockWidget::relayout()
{
   if( layout )
      delete layout;
  if(height() < 32)
  {
     layout = new QHBoxLayout(this);
     if( type == "Digital" )
     {
        layout->addWidget(clock);
        layout->addStretch();
        layout->addWidget(date);
        layout->addStretch();
     }
     else
     {
        layout->addWidget(clock);
        layout->addSpacing(3);
        layout->addWidget(date);
        layout->addStretch();
     }
  }
  else
  {
     layout = new QVBoxLayout(this);
     if( type == "Digital" )
     {
        layout->addWidget(clock);
        layout->addStretch();
        layout->addWidget(date);
        layout->addStretch();
     }
     else
     {
        layout->addWidget(clock, 2);
        layout->addStretch();
        layout->addWidget(date);
//        layout->addStretch();
     }
  }

}

void ClockWidget::mousePressEvent(QMouseEvent *ev)
{
    if(ev->button() == QMouseEvent::LeftButton)
        slotDatePicker();
    if(ev->button() == QMouseEvent::RightButton)
       slotContextMenu();
}


void ClockWidget::slotDatePicker()
{
    if ( cal ) {
        cal->close();
        return;
    }

    cal = new DatePicker;
    connect( cal, SIGNAL( destroyed() ), SLOT( slotCalendarDeleted() ));
    Position p = position();
    QRect deskR = QApplication::desktop()->rect();

    // some extra spacing is included if aligned on a desktop edge
    QPoint c;
    if(p == InternalApplet::Bottom){
        c = mapToGlobal(pos());
        c.setY(c.y()-cal->height()-2);
        if(c.x() + cal->width() > deskR.right())
            c.setX(deskR.right()-cal->width()-1);
    }
    else if(p == InternalApplet::Top){
        c = mapToGlobal(pos());
        c.setY(c.y()+height()+2);
        if(c.x() + cal->width() > deskR.right())
            c.setX(deskR.right()-cal->width()-1);
    }
    else if(p == InternalApplet::Left){
        c = mapToGlobal(pos());
        c.setX(c.x()+width()+2);
        if(c.y() + cal->height() > deskR.bottom())
            c.setY(deskR.bottom()-cal->height()-1);
    }
    else{ // right
        c = mapToGlobal(pos());
        c.setX(c.x()-cal->width()-2);
        if(c.y() + cal->height() > deskR.bottom())
            c.setY(deskR.bottom()-cal->height()-1);
    }
    cal->move(c);
    qApp->processEvents(); // make sure it is moved before showing
    cal->show();
}

void ClockWidget::slotContextMenu()
{
   KPopupMenu menu;
   int result;
   menu.insertTitle( i18n( "Type" ) );
   menu.insertItem( i18n( "analog" ), 0, 1 );
   menu.insertItem( i18n( "digital" ), 1, 2 );
   result = menu.exec( QCursor::pos( ) );

    
   if( result == 0 )
   {
      AnalogClock* aclock;
      delete layout;
      layout = 0;
      delete clock;
      clock = 0;

      aclock = new AnalogClock(this);
      connect(aclock, SIGNAL(datePicker()), SLOT(slotDatePicker()));
      connect(aclock, SIGNAL(contextMenu()), SLOT(slotContextMenu()));
      clock = aclock;
      
      type = "Analog";
      relayout();
      clock->show();
   }
   else if( result == 1 )
   {
      Clock* dclock;

      delete layout;
      layout = 0;
      delete clock;
      clock = 0;
      
      dclock = new Clock(this);
      connect(dclock, SIGNAL(datePicker()), SLOT(slotDatePicker()));
      connect(dclock, SIGNAL(contextMenu()), SLOT(slotContextMenu()));
      clock = dclock;

      type = "Digital";
      relayout();
      clock->show();
   }
   KConfig *config = KGlobal::config();
   config->setGroup("koolclock");
   config->writeEntry( "Type", type );
}

void ClockWidget::slotCalendarDeleted()
{
    cal = 0L;
}

ClockWidget::~ClockWidget( )
{
}


AnalogClock::AnalogClock(QWidget *parent, const char *name)
    : QWidget(parent, name)
{

    /*
    KConfig *config = KGlobal::config();

    config->setGroup("kaclock");

    QColorGroup cg = colorGroup();
    QColor color = config->readColorEntry("LCDForeground", &Qt::green);
    cg.setColor(QColorGroup::Foreground, color);
    color = config->readColorEntry("LCDBackground", &Qt::black);
    cg.setColor(QColorGroup::Background, color);
    setPalette(QPalette(cg, cg, cg));
    */
    
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(slotTimer()));
    slotTimer();
    timer->start(1000);
    setMinimumSize( 16, 16 );
}

void AnalogClock::slotTimer()
{
    time = QTime::currentTime( );

    repaint( );
}

void AnalogClock::paintEvent( QPaintEvent * )
{
  if ( !isVisible() )
    return;

  QPainter paint;
  paint.begin( this );

  QPointArray pts;
  QPoint cp = rect().center();
  int d = QMIN(width(),height());
  paint.setPen( gray );
  paint.setBrush( gray );
  paint.setViewport(2,2,width(),height());

  for ( int c=0 ; c < 2 ; c++ )
    {
      QWMatrix matrix;
      matrix.translate( cp.x(), cp.y() );
      matrix.scale( d/1000.0F, d/1000.0F );

      // hour 
      float h_angle = 30*(time.hour()%12-3) + time.minute()/2;
      matrix.rotate( h_angle );
      paint.setWorldMatrix( matrix );
      pts.setPoints( 4, -20,0,  0,-20, 300,0, 0,20 );
      paint.drawPolygon( pts );
      matrix.rotate( -h_angle );

      // minute
      float m_angle = (time.minute()-15)*6;
      matrix.rotate( m_angle );
      paint.setWorldMatrix( matrix );
      pts.setPoints( 4, -10,0, 0,-10, 400,0, 0,10 );
      paint.drawPolygon( pts );
      matrix.rotate( -m_angle );

      // second
      float s_angle = (time.second()-15)*6;
      matrix.rotate( s_angle );
      paint.setWorldMatrix( matrix );
      pts.setPoints(4,0,0,0,0,400,0,0,0);
      paint.drawPolygon( pts );
      matrix.rotate( -s_angle );

      QWMatrix matrix2;
      matrix2.translate( cp.x(), cp.y() );
      matrix2.scale( d/1000.0F, d/1000.0F );
      // quadrante
      for ( int i=0 ; i < 12 ; i++ )
        {
          paint.setWorldMatrix( matrix2 );
          paint.drawLine( 460,0, 500,0 );	// draw hour lines
//          paint.drawEllipse( 450, -15, 30, 30 );
          matrix2.rotate( 30 );
        }

      paint.setPen( black );
      paint.setBrush( black );
      paint.setViewport(0,0,width(),height());
    }
  paint.end();
}

void AnalogClock::mousePressEvent(QMouseEvent *ev)
{
    if(ev->button() == QMouseEvent::LeftButton)
        emit datePicker();
    if(ev->button() == QMouseEvent::RightButton)
       emit contextMenu();
}


#include "clock.moc"
