#include "VideoReconstruction.h"
#include "../OpenCV/lib/cvlink.h"
#include "cxcore.h"
#include "highgui.h"
#include "cv.h"
#include "FileNameFunctions.h"
#include "ImageConversion.h"
#include <Windows.h>
#include "PoissonRecon.h"
#include "TriMesh.h"
#include <Eigen/Eigen>
#include "ZImage.h"

namespace DFF_VideoMat
{



CVideoReconstruction* CVideoReconstruction::m_instance = NULL;

CVideoReconstruction::CVideoReconstruction(const char* configfile)
{
	m_configFile = std::string(configfile);
}

CVideoReconstruction::~CVideoReconstruction()
{
	if(m_instance)
		delete m_instance;

	m_instance = NULL;
}

CVideoReconstruction* CVideoReconstruction::GetInstance(const char* configfile)
{
	if(m_instance == NULL)
		m_instance = new CVideoReconstruction(configfile);

	return m_instance;
}
bool CVideoReconstruction::Init()
{
	if(!m_parameterParser.ReadParaFile(m_configFile.c_str()))
		return false;

	if(!m_actsParser.LoadProject(m_parameterParser.m_actfile))
		return false;
	
	for(int index_frame = 0;index_frame<m_actsParser.m_frameCount;index_frame++)
	{
		CCameraFrame tmp_camera;
		tmp_camera.SetK(m_actsParser.m_fx,m_actsParser.m_fy,m_actsParser.m_cx,m_actsParser.m_cy,m_actsParser.m_skew);
		tmp_camera.SetObjAbsRT(m_actsParser.m_extrinsicParas[index_frame]);
		m_cameraFrames.push_back(tmp_camera);
	}

	m_colorImage_Path_Name = m_actsParser.m_imgPath;
	int tmp_num = CFileNameFunctions::find_FileName_Number(m_colorImage_Path_Name);

	if(tmp_num == -1)
		return false;
	

	m_depthImage_Path_Name = CFileNameFunctions::find_FileName_Dir(m_parameterParser.m_actfile)+"DATA/_depth0.raw";

	m_reconstructPath = CFileNameFunctions::find_FileName_Dir(m_parameterParser.m_actfile)+"Rec/";
	CreateDirectoryA(m_reconstructPath.c_str(), 0);


	ZByteImage colorImg = LoadColorImage(0);
	if(!colorImg.IsValid())
		return false;
	m_imgSize[0] = colorImg.GetWidth();
	m_imgSize[1] = colorImg.GetHeight();

	return true;
}

ZFloatImage CVideoReconstruction::LoadDepthImage(int index)
{
	std::string dspMapName = CFileNameFunctions::increase_FileName_Number(m_depthImage_Path_Name,index);
	return ZImageFunc::LoadFloatImage(m_imgSize[0],m_imgSize[1],dspMapName);
}
ZByteImage CVideoReconstruction::LoadColorImage(int index)
{
	int color_index = m_actsParser.m_startFrame + index*m_actsParser.m_step;
	std::string colorImgName = CFileNameFunctions::increase_FileName_Number(m_colorImage_Path_Name,color_index);
	return ColorImageFunc::LoadColorImg(colorImgName);
}




bool CVideoReconstruction::PointCloudReconstruct()
{

	return true;
}


bool CVideoReconstruction::MeshReconstruct()
{
	return true;
}







bool CVideoReconstruction::Reconstruction()
{
	std::cout<<"Reconstructing Point Cloud...\n";
	if(!PointCloudReconstruct())
		return false;
	
	std::cout<<"Reconstructing Mesh...\n";
	if(!MeshReconstruct())
		return false;

	return true;
}

bool CVideoReconstruction::Execute()
{
	return Reconstruction();
	return true;

}

}