#include "clMemoryClass.h"

//--------------------------------------------------------
//----------           clMemoryClass          ------------
//--------------------------------------------------------
// -------------------------------------------------------

// -------------------------------------------------------
//! \brief  メモリオブジェクトのクラスの初期化.
//! \param  なし.
//! \return なし.
clMemoryClass::clMemoryClass()
{
	__CONSTRUCTOR;
}

// -------------------------------------------------------
//! \brief  メモリを破棄した時の処理.
//! \param  なし.
//! \return なし.
clMemoryClass::~clMemoryClass()
{
	__DESTRUCTOR;
	for(unsigned int i=0; i<memory.size(); ++i){
		clReleaseMemObject(memory[i]);
	}
}

// -------------------------------------------------------
//! \brief  メモリを作成する.
//! \param  なし.
//! \return なし.
void clMemoryClass::createMemory(cl_context   context,
	                             cl_mem_flags flag,
								 size_t       memroy_size,
								 void         *mem_pointer,
								 std::string  mem_name)
{try{
	cl_int status;
	this->memory_name.push_back(mem_name);
	this->memory.push_back(
		clCreateBuffer(context,
					   flag,
					   memroy_size,
					   mem_pointer,
					   &status)
	);

	if(status != CL_SUCCESS){
		std::stringstream a;
		a << mem_name << " create buffer object failed.";
		throw clErrorClass(status, a.str(), __FUNCTION__);
	}
}
catch(clErrorClass &err){err.showErrMsg();}catch(...){std::cerr << "unknown error." << std::endl;}}

cl_mem *clMemoryClass::getMemory(unsigned int index)
{
	return &memory[index];
}

cl_mem *clMemoryClass::getMemory(std::string name)
{
	return &memory[getMemoryIndex(name)];
}

unsigned int clMemoryClass::getMemoryIndex(std::string name)
{
    unsigned int index=0;
    for(index=0; index<memory_name.size(); ++index){
        if(memory_name[index] == name){
            goto LOOP_SUCCESS;
        }
    }
    index = 0;
    std::cerr << __FUNCTION__  << std::endl <<  "unknown memory object." << std::endl;
LOOP_SUCCESS:
    return index;
}
