/*  DS
 *  Copyright (C) Joakim Kolsjö and Anders Asplund 2005
 *	This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
 */ 
 
#include "textureloader.h"

using namespace std;

namespace DS
{
	TextureLoader::TextureLoader(DataReader* pDataReader)
	{
		m_pDataReader = pDataReader;
	}
	
	TextureLoader::~TextureLoader()
	{
		std::map <std::string, Image*>::iterator iter = m_TextureHandles.begin();
		while(iter != m_TextureHandles.end())
		{
			delete iter->second;
			++iter;
		}
		
		std::map <std::string, GLuint>::iterator titer = m_Textures.begin();
		while(titer != m_Textures.end())
		{
			glDeleteTextures(1, &titer->second);
			++titer;
		}		
		
		m_Textures.clear();
		m_TextureHandles.clear();
	}
	
	void TextureLoader::Load(const char* pFile)
	{
		if(!m_TextureHandles[pFile])
		{
			Image* pImage = new Image;
			try {
				pImage->Load(pFile, m_pDataReader->GetFile(pFile));
			} catch (Exception e) {
				delete pImage;
				throw Exception(e.GetFunctionName(), e.GetMessage());
			}

			m_TextureHandles[pFile] = pImage;
			m_Textures[pFile] = 0;
		}
	}
	
	GLuint TextureLoader::GetTexture(const char* pFile)
	{
		if(!m_TextureHandles[pFile])
			Load(pFile);
		
		if(!m_Textures[pFile])
			m_Textures[pFile] = m_TextureHandles[pFile]->MakeGL();
		
		return m_Textures[pFile];
	}
}
