#include <qfiledlg.h>
#include <qfile.h>
#include <kapp.h>
#include <ktoolbar.h>
#include <kmenubar.h>
#include <kiconloader.h>
#include <qmsgbox.h>
#include <qstring.h>
#include "kpipewidget.h"
#include "playfield.h"
#include "status.h"


KPipeWidget::KPipeWidget(QWidget *parent, const char *name) : QWidget(parent, name)
{
  
  startDelay=35;
  pumpingTime=250;
  inGame=false;

  status=new Status(this,"status");
  status->setGeometry(10,0,80,500);
 
  field= new PlayField(this,"feld");
  field->setGeometry(85,0,520,550);

  timer=new QTimer(this);
  //timer->changeInterval(1000);
  time=new QTime();

  status->show();
  field->show();

  connect(status, SIGNAL(nextLink(PipeButton::LinkType)), 
          field, SLOT(linkToBuild(PipeButton::LinkType)));

  connect(field, SIGNAL(requireLink()), 
          status, SLOT(linkRequired()));

  connect(this, SIGNAL(startGame()),
	  status, SLOT(gameStarted()));
  connect(this, SIGNAL(startGame()),
	  field, SLOT(gameStarted()));

  connect(timer, SIGNAL(timeout()),
	  this, SLOT(timerEvent()));

  connect(this, SIGNAL(pumpingEvent()),
	  field, SLOT(flowEvent()));
  
 connect(field, SIGNAL(gameOver()), 
         this, SLOT(endGame()));

 connect(field, SIGNAL(gameOver()), 
         status, SLOT(gameOver()));

 connect(field, SIGNAL(scoreChanged(int)),
	 status, SLOT(scoreChanged(int)));
 // show();
}

KPipeWidget::~KPipeWidget()
{
  delete(field);
  delete(status);
  delete(timer);
  delete(time);
}

void KPipeWidget::newGame()
{
  if(timer->isActive())    timer->stop();
 
  isFlowing=false;
  time->start();
  timer->start(1000);
  status->timeLCD->display(startDelay);
  inGame=true;
  emit startGame();
}

void KPipeWidget::endGame()
{
  timer->stop();
  inGame=false;
  QMessageBox::about(0, 0, klocale->translate("Game over!"));
}

void KPipeWidget::closeEvent(QCloseEvent *e)
{
    e->accept();
}

void KPipeWidget::timerEvent()
{
  if(!isFlowing)
    {
      int elapsed=startDelay-(time->elapsed())/1000;
      
      if(elapsed>=0)
	status->timeLCD->display(elapsed);
      else
	{
	  // Pro Intervall fliesst es fuenf Pixel weit,
	  // nach zehn solcher Schritte ist das Link voll.
	  timer->changeInterval(pumpingTime);
	  isFlowing=true;
	}
    }
  
  if(isFlowing) emit pumpingEvent();
}

void KPipeWidget::beginner()
{
  if(inGame) return;
  pumpingTime=250; // 
  startDelay=35;
}

void KPipeWidget::advanced()
{
  if(inGame) return;
  pumpingTime=180; // 
  startDelay=30;
}

void KPipeWidget::expert()
{
  if(inGame) return;
  pumpingTime=120; // 
  startDelay=20;
}

void KPipeWidget::showHighscores()
{
  status->showHighscores();
}
void KPipeWidget::oil()
{
  field->setFluid(PlayField::Oil);
}

void KPipeWidget::water()
{
  field->setFluid(PlayField::Water);
}

void KPipeWidget::acid()
{
  field->setFluid(PlayField::Acid);
}
