/*
    QGLView
    Ivan Pelipenko peri4ko@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "gltexture_manager.h"


bool GLTextureManager::loadTextures() {
	// glGenTextures();
	QFileInfoList fil;
	Animation anim;
	for (int i = 0; i < anim_pathes.size(); ++i) {
		anim.path = anim_pathes[i].second;
		anim.bitmaps.clear();
		fil = QDir(anim_pathes[i].first).entryInfoList(QDir::Files, QDir::Name);
		foreach(const QFileInfo & fi, fil) {
			if (fi.baseName().indexOf(anim_pathes[i].second) < 0) continue;
			anim.bitmaps << loadTexture(fi.filePath(), false);
		}
		qDebug() << "[TextureManager] Loaded" << anim.bitmaps.size() << "frames";
		anim_ids << QPair<QString, Animation>(anim_pathes[i].second, anim);
	}
	anim_pathes.clear();
	foreach(const QString & i, tex_pathes)
		loadTexture(i, true);
	tex_pathes.clear();
	return true;
}


void GLTextureManager::deleteTextures() {
	for (int i = 0; i < 2; ++i) {
		QList<GLuint> texs = tex_ids[i].values();
		qDebug() << "[TextureManager] Delete" << texs.size() << "textures";
		if (!texs.isEmpty()) glDeleteTextures(texs.size(), &texs[0]);
		tex_ids[i].clear();
	}
	qDebug() << "[TextureManager] Delete" << anim_ids.size() << "animations";
	for (int i = 0; i < anim_ids.size(); ++i)
		glDeleteTextures(anim_ids[i].second.bitmaps.size(), anim_ids[i].second.bitmaps.data());
	anim_ids.clear();
}


void GLTextureManager::deleteTexture(const QString & name) {
	for (int i = 0; i < 2; ++i) {
		if (tex_ids[i].contains(name)) {
			GLuint id = tex_ids[i][name];
			glDeleteTextures(1, &id);
			tex_ids[i].remove(name);
		}
	}
}
