//mactexturesimport.cpp
//mac-specific (or rather "QuickTime-Specific") code to load textures

#include <OpenGL/gl.h>
#include <QuickTime/QuickTime.h>
#include <string.h>
#include "fileio.h"
#include "error.h"
#include "gamemem.h"
#include "texturesimport.h"
#include "network.h"

typedef struct{
	UInt8 r,g,b,a;
}tRGBAColor;

typedef struct{
	UInt8 a,r,g,b;
}tARGBColor;

void *TexturesLoadImportBuffer(tFileRef tex,int *xSize,int *ySize)
{
	ComponentInstance gi;
	int gotImage=false;
	char *fileExtension=FileGetExtension(tex);
	
	if(!_stricmp(fileExtension,kFileTypeImageURL)){
		tImageURL *url=(tImageURL*)FileGetParsedDataPtr(tex,kParserTypeImageURL,sizeof(tImageURL));
		Handle dataRef=NewHandle(strlen(url->url)+1);
		strcpy(*dataRef,url->url);
		
		if(!gInternetAvailable)
			tex=url->offlineImage;	
		else if(GetGraphicsImporterForDataRef(dataRef,URLDataHandlerSubType,&gi)!=noErr)
			tex=url->offlineImage;	
		else
			gotImage=true;
	}
	if(!gotImage)	
	{
		void *textureData=FileGetDataPtr(tex);
		Handle dataHandle,dataRef;
		int size=FileGetSize(tex);
		
		//Get a Handle with the texture file data in it
		PtrToHand(textureData,&dataHandle,FileGetSize(tex));

		char *name=FileGetName(tex);
		unsigned char len=strlen(name);

		//create a new data reference
		dataRef=NewHandle(sizeof(Handle)+len+1);
		*((Handle*)(*dataRef))=dataHandle;
		BlockMoveData(name,*dataRef+sizeof(Handle)+1,len);
		*(unsigned char*)(*dataRef+sizeof(Handle))=len;
		HandleError(GetGraphicsImporterForDataRef(dataRef,HandleDataHandlerSubType,&gi));
	}
	
//	GWorldPtr oldGW;
//	GDHandle oldGD;
//	GetGWorld(&oldGW,&oldGD);
	
	//get image bounds
	Rect bounds;
	HandleError(GraphicsImportGetNaturalBounds(gi,&bounds));
	*xSize=bounds.right-bounds.left;
	*ySize=bounds.bottom-bounds.top;
	
	//create a buffer to hold the decompressed pixel data
	int rowBytes=*xSize*4;
	void *imageBuffer=MemoryAllocateBlock(*ySize*rowBytes);
	
	//create a GWorld structure for the pixel buffer
	GWorldPtr imageGW;
	QTNewGWorldFromPtr(&imageGW,k32ARGBPixelFormat,&bounds,nil,nil,0,imageBuffer,rowBytes);
	
	//Set up graphics importer
	HandleError(GraphicsImportSetGWorld(gi,imageGW,nil));
	HandleError(GraphicsImportSetQuality(gi,codecLosslessQuality));
	
	//decompress the image to the GWorld
	LockPixels(GetGWorldPixMap(imageGW));
	HandleError(GraphicsImportDraw(gi));
	UnlockPixels(GetGWorldPixMap(imageGW));

	//convert ARGB to RGBA
	for(int i=0;i<*ySize*rowBytes/4;i++)
	{
		tARGBColor buf=*(((tARGBColor*)imageBuffer)+i);
		tRGBAColor c;
		c.a=buf.a;
		c.r=buf.r;
		c.g=buf.g;
		c.b=buf.b;
		*(((tRGBAColor*)imageBuffer)+i)=c;
	}
	
	//re-set the GWorld to use.
//	SetGWorld(oldGW,oldGD);

	//dispose our structures.
	DisposeGWorld(imageGW);
	CloseComponent(gi);
	
	return imageBuffer;
}

