/*
    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 "loader_qgl.h"

#include "chunkstream.h"


GLObjectBase * loadFromQGLFile(const QString & filepath) {
	QFile f(filepath);
	if (!f.exists()) {
		qDebug() << "[Loader QGL] Error: can`t open \"" + filepath + "\"";
		return 0;
	}
	f.open(QIODevice::ReadOnly);
	QDataStream s(&f);
	s.setVersion(QDataStream::Qt_4_8);
	char sign[4];
	s.readRawData(sign, 4);
	if ((sign[0] != 'Q') || (sign[1] != 'G') || (sign[2] != 'L') || (sign[3] != 'F')) {
		qDebug() << "[Loader QGL] Error: \"" + filepath + "\" is not valid QGL file!";
		return 0;
	}
	GLObjectBase * root = 0;
	ushort version      = 0xFFFF;
	f.peek((char *)&version, 2);
	if (version == 1) {
		s.skipRawData(2);
		s >> root;
	} else {
		qDebug() << "[Loader QGL] Error: \"" + filepath + "\" unsupported version!";
		return 0;
	}
	root->buildTransform();
	if (root->name().isEmpty()) root->setName(QFileInfo(f).baseName());
	qDebug() << "[Loader QGL] Loaded" << root->childCount() << "objects from" << filepath;
	return root;
}


bool saveToQGLFile(const QString & filepath, const GLObjectBase * o) {
	QFile f(filepath);
	if (!f.open(QIODevice::ReadWrite)) return false;
	f.resize(0);
	QDataStream s(&f);
	s.setVersion(QDataStream::Qt_4_8);
	char sign[4]   = {'Q', 'G', 'L', 'F'};
	ushort version = 1;
	s.writeRawData(sign, 4);
	s.writeRawData((char *)&version, 2);
	s << o;
	return true;
}
