/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


		#include "picture/pict_io.h"
		#include "picture/pict.h"
		#include "filesystem/io_handle.h"
		#include "filesystem/filesystem.h"
		#include "memory/nauto_ptr.h"
		#include "platform.h"
		#include "log/log.h"

		using namespace GS;
		using namespace GS::IO;

		template<> PictureIO *Singleton <PictureIO> ::i = NULL;


//------------------------------------------------------------------------------
PictureCodec		*PictureIO::Codec(const char *codec_name)
{
	ListForeachPtr(PictureCodec *, codec, codec_list)
		if	(GS::String(codec->GetName()) == GS::String(codec_name))
			return codec;
	return NULL;
}
bool				PictureIO::RegisterCodec(PictureCodec *codec, bool verbose)
{
	if	(Codec(codec->GetName()))
		return false;
	codec_list.Add(codec);
	if	(verbose)
		__LOG__ << "Codec '" << codec->GetName() << "' registered successfully.\n";
	return true;
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
bool				PictureIO::Save(const Picture &picture, const char *uri, const char *codec_name)
{
	if	(PictureCodec *c = Codec(codec_name))
	{
		AutoPtr <Handle> h(Platform::Get().io->Open(uri, ModeWrite));
		if	(h.IsNull())
			return false;

		if	(!c->Save(*h, picture))
			return false;
	}
	else
		return false;

	return true;
}
bool				PictureIO::Load(Picture &picture, const char *uri)
{
	AutoPtr <Handle> h(Platform::Get().io->Open(uri));
	if	(h.IsNull())
		return false;

	picture.name = uri;
	ListForeachPtr(PictureCodec *, codec, codec_list)
		if	(codec->Load(*h, picture))
			return true;

	return false;
}
//------------------------------------------------------------------------------
