#include "Image.h"
#include "DataArray.h"

using gge::resource::ReadFrom;

namespace gorgon {

	Image *LoadImage(Base *parent, File &file, std::istream &in, int Size) {
		Image &img=*new Image;
		if(parent)
			img.SetParent(*parent);
		else
			img.RemoveParent();


		std::vector<namecaption> names;

		LoadEntries(in, Size, file, img, [&](GID::Type &gid, int size) -> bool {
			switch(gid) {
			case gge::resource::GID::Image_Props:
				img.LoadProperties(in, size);
				return true;
			case gge::resource::GID::Image_Cmp_Props:
				//gorgon does not support this yet (lzma image compression will not work)
				//!TODO
				return true;
			case gge::resource::GID::Image_Data:
				img.LoadData(in, size);
				return true;
			case gge::resource::GID::Image_Cmp_Data:
				img.LoadData(in, size);
				return true;
			}

			return false;
		}, names);

		return &img;
	}

	DataArray *LoadData(Base *parent, File &file, std::istream &in, int Size) {
		DataArray &data=*new DataArray;
		if(parent)
			data.SetParent(*parent);
		else
			data.RemoveParent();


		std::vector<namecaption> names;
		unsigned ind=0;

		LoadEntries(in, Size, file, data, [&](GID::Type &gid, int size) -> bool {
			if(gid==gge::resource::GID::Data_Names) {
				LoadNames(in, size,names,gge::resource::GID::Data_Name);
				return true;
			}

			std::string cap;
			if(ind<names.size())
				cap=names[ind++].caption;

			switch(gid) {
			case gge::resource::GID::Data_Int:
				data.Add(ReadFrom<int>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Color:
				data.Add(ReadFrom<gge::graphics::RGBint>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Float:
				data.Add(ReadFrom<float>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Text: {
				std::string tmp;
				if(size) {
					tmp.resize(size);
					in.read(&tmp[0], size);
				}
				data.Add(tmp).name=cap;
				return true;
			}
			case gge::resource::GID::Data_Point:
				data.Add(ReadFrom<gge::utils::Point>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Size:
				data.Add(ReadFrom<gge::utils::Size>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Rect:
				data.Add(ReadFrom<gge::utils::Rectangle>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Bounds:
				data.Add(ReadFrom<gge::utils::Bounds>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Margins:
				data.Add(ReadFrom<gge::utils::Margins>(in)).name=cap;
				return true;
			case gge::resource::GID::Data_Font: {
				FontInitiator f;
				ReadFrom<int>(in);//useless gid
				f=FontInitiator::Load(file, in, ReadFrom<int>(in));
				data.Add(*new FontData(f)).name=cap;

				return true;
			}
			case gge::resource::GID::Data_Link:
				gge::utils::SGuid guid;
				guid.Load(in);
				data.Add(*new LinkData(guid)).name=cap;

				return true;
			}

			return false;
		}, names);

		return &data;
	}

}
