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

#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 "CProgressDialog.h"

#include "CRunThread.h"

CRunThread::CRunThread( CRenderObj*       surfaceobj,
                        const QString&    filename,
                        unsigned int      stackSize)
  : QThread(stackSize), m_ProgressLabel("")
{
  m_pSurfaceObj = surfaceobj;
  m_filename    = filename;

  m_Progress    = 0;
  m_end         = false;
}


void CRunThread::run(void)
{
  m_pSurfaceObj->Update();

  // Number of lines after which the progress dialog is updated,
  // once every percent.
  int NbLinesUpdate =
    m_pSurfaceObj->m_Height / 100 +
    (m_pSurfaceObj->m_Height % 100 ? 1 : 0);

  CColor TempColor;
  CImage image(m_pSurfaceObj->m_Width, m_pSurfaceObj->m_Height);

  m_ProgressLabel = "Ray tracing started...";

  for (int j = m_pSurfaceObj->m_Height - 1; j >= 0 ; --j)
    {
      for (int i = m_pSurfaceObj->m_Width - 1; i >= 0 ; --i)
        {
          if (m_end)
            QThread::exit();

          TempColor = m_pSurfaceObj->GetPixelColor(i, j);
          TempColor.Clamp();

          image(i,j,0) = TempColor[0];
          image(i,j,1) = TempColor[1];
          image(i,j,2) = TempColor[2];
        }

      if (j % NbLinesUpdate == 0)
        {
          m_Progress = 100 - (100 * j) / m_pSurfaceObj->m_Height;
        }
    }

  m_ProgressLabel = "File writing started...";

  switch(image.WriteBmpFile(m_filename.ascii()))
    {
    case 0:
      {
        m_ProgressLabel = "Job done";
        break;
      }
    case -1:
      {
        m_ProgressLabel = "Error: unable to open file '";
        m_ProgressLabel += m_filename;
        m_ProgressLabel += "'";
        break;
      }
    default:
      {
        m_ProgressLabel = "Error occured while writing to file";
        break;
      }
    }
}
