#include <cmath>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

#include <qtimer.h>

#include "popassert.h"
#include "CVector3f.h"
#include "CColor.h"
#include "CImage.h"
#include "CVectBase.h"
#include "compute.h"
#include "CMathExpression.h"
#include "CRenderObj.h"
#include "CRunThread.h"

#include "CProgressDialog.h"

CProgressDialog::CProgressDialog(const CRenderObj& surfaceobj,
                                 const QString& filename,
                                 const QString& labelText,
                                 const QString& cancelButtonText,
                                 int totalSteps,
                                 QWidget *creator,
                                 const char *name,
                                 bool modal,
                                 WFlags f)
  : QProgressDialog(labelText, cancelButtonText, totalSteps,
                    creator, name, modal, f)
{
  m_pSurfaceObj = new CRenderObj(surfaceobj);
  m_pRunThread = new CRunThread(m_pSurfaceObj, filename);
  m_pRunThread->start();

  connect(this , SIGNAL(canceled()),
          this , SLOT(Closed()));

  m_pTimer = new QTimer( this );
  connect( m_pTimer, SIGNAL(timeout()), this, SLOT(Update()) );
  m_pTimer->start( 100 );
}

CProgressDialog::~CProgressDialog()
{
  m_pTimer->stop();
  delete m_pTimer;

  if (m_pRunThread->running())
    m_pRunThread->end();

  while (m_pRunThread->running());

  delete m_pRunThread;
  delete m_pSurfaceObj;
}


void CProgressDialog::Update()
{
  if (m_pRunThread)
    {
      setLabelText(m_pRunThread->getProgressLabel());
      setProgress(m_pRunThread->getProgress());
      if (m_pRunThread->getProgress() == 100)
        setCancelButtonText("&Ok");
    }
}
