#include "countdown.h"

Countdown::Countdown( QWidget *parent ) : QWidget( parent )
{
  //Layout
  QGridLayout *gLayout = new QGridLayout( this );
  QLabel *label = new QLabel( tr( "Time: " ) );
  QFont font = label->font();
  font.setBold( true );
  label->setFont( font );
  gLayout->addWidget( label, 0, 0 );
  timeLCD = new QLCDNumber( 2 );
  gLayout->addWidget( timeLCD, 0, 1 );

  //Timer
  timer = new QTimer( this );
  connect( timer, SIGNAL( timeout() ), timer, SLOT( stop() ) );
  connect( timer, SIGNAL( timeout() ), this, SIGNAL( timeout() ) );
  timerLCD = new QTimer( this );
  connect( timerLCD, SIGNAL( timeout() ), this, SLOT( showRemainingTime() ) );
  connect( timerLCD, SIGNAL( timeout() ), timerLCD, SLOT( start() ) );
  connect( this, SIGNAL( timeout() ), timerLCD, SLOT( stop() ) );
  timerLCD->setInterval( 1000 );
}

void Countdown::start( int countdownTime )
{
  this->countdownTime = countdownTime;
  timer->setInterval( this->countdownTime * 1000 );
  timer->start();
  showRemainingTime();
  timerLCD->start();
}

void Countdown::showRemainingTime( void )
{
    timeLCD->display( ( int ) timer->remainingTime() / 1000 );
}

void Countdown::restart( void )
{
  timer->start();
  showRemainingTime();
  timerLCD->start();
}

void Countdown::stop()
{
  if( timer->isActive() ) timer->stop();
  if( timerLCD->isActive() ) timerLCD->stop();
}

int Countdown::getUsedTime( void )
{
  return ( timer->interval() - timer->remainingTime() ) / 1000;
}
