/****************************/
/*        FILE              */
/* (c)2002 Pangea Software  */
/* By Brian Greenstone      */
/****************************/


/***************/
/* EXTERNALS   */
/***************/

//#include <dialogs.h>
//#include <CFBase.h>
//#include <CFString.h>
//#include <cstdlib>
//#include <cstring>

extern	Boolean			gExportLayersSeparate;


/****************************/
/*    PROTOTYPES            */
/****************************/

pascal void myEventProc(NavEventCallbackMessage callBackSelector, NavCBRecPtr callBackParms,
						NavCallBackUserData callBackUD);
pascal Boolean myFilterProc(AEDesc*theItem,void*info, NavCallBackUserData callBackUD, NavFilterModes filterMode);



/****************************/
/*    CONSTANTS             */
/****************************/


/**********************/
/*     VARIABLES      */
/**********************/

FSSpec		gSharedLibSpec;
short		gLibResRefNum = -1;
short		gRestoreResRefNum;


static u_long			gNavFilterFileType = 0;

static FSSpec			gNavRecentSpec = {0,0,0};

static	Boolean			gHasDoneInitFile = false;

FSSpec			gExportSpec;


/******************* INIT FILE ************************/

void InitFile(void)
{
	if (!gHasDoneInitFile)
	{
		gNavRecentSpec.vRefNum = 0;
		gNavRecentSpec.parID = 0;
		
		gHasDoneInitFile = true;
	}
}



#pragma mark -


/************************ NAV SERVICES:  EVENT PROC *****************************/

pascal void myEventProc(NavEventCallbackMessage callBackSelector, NavCBRecPtr callBackParms,
						NavCallBackUserData callBackUD)
{
#pragma unused (callBackUD)
	
	switch (callBackSelector)
	{
		case	kNavCBEvent:
				switch (((callBackParms->eventData).eventDataParms).event->what)
				{
					case 	updateEvt:
//							MyHandleUpdateEvent(window, (EventRecord*)callBackParms->eventData.event);
							break;
				}
				break;
	}
}


/************************ NAV SERCIES: MY FILTER PROC **************************/

pascal Boolean myFilterProc(AEDesc*theItem,void*info, NavCallBackUserData callBackUD, NavFilterModes filterMode)
{
Boolean display 			= true;
NavFileOrFolderInfo	*theInfo = (NavFileOrFolderInfo*)info;

#pragma unused (callBackUD, filterMode)

	if (gNavFilterFileType == 0)						// see if no filter
		return(true);


	if (theItem->descriptorType == typeFSS)
		if (!theInfo->isFolder)
			if (theInfo->fileAndFolder.fileInfo.finderInfo.fdType != gNavFilterFileType)			// only show us the saved games
				display = false;
				
	return display;
}




/********************** PUT FILE WITH NAV SERVICES *************************/

OSErr PutFileWithNavServices(FSSpecPtr defaultLocationfssPtr, NavReplyRecord *reply, FSSpec *outSpec)
{
OSErr 				anErr 			= noErr;
NavDialogOptions 	dialogOptions;
OSType 				fileTypeToSave 	='xxxx';
OSType 				creatorType 	='BG3D';
AEDesc 				defaultLocation;

	MyFlushEvents();

	anErr = NavGetDefaultDialogOptions(&dialogOptions);
	if (anErr == noErr)
	{
		if (gExportLayersSeparate)
			dialogOptions.savedFileName[0] = 0;
		else
			CopyPStr(defaultLocationfssPtr->name, dialogOptions.savedFileName);					// set default name

				/* make descriptor for default location */

		dialogOptions.dialogOptionFlags |= kNavSelectDefaultLocation;	// Set default location option				

		anErr = AECreateDesc(typeFSS,defaultLocationfssPtr, sizeof(FSSpec), &defaultLocation);

		
		anErr = NavPutFile(&defaultLocation, reply, &dialogOptions, nil, fileTypeToSave, creatorType, nil);
		if ((anErr == noErr) && (reply->validRecord))
		{
			AEKeyword	theKeyword;
			DescType 	actualType;
			Size 		actualSize;
			
			anErr = AEGetNthPtr(&(reply->selection),1,typeFSS, &theKeyword,&actualType, outSpec, sizeof(FSSpec), &actualSize);
		}
		AEDisposeDesc(&defaultLocation);				
	}

	if (!anErr)
		gNavRecentSpec = *outSpec;					// remember where it was

	return anErr;
}


#pragma mark -

/******************* GET EXPORT FILE NAME *************************/

OSErr GetExportFileName(void)
{
Str255	mayaFile;
OSErr	iErr;
FSSpec	mayaSpec;
NavReplyRecord	reply;
int		i;

			/* GET SPEC FOR SRC MAYA FILE */
			
	Maya_GetCurrentFileName(mayaFile);				// get full path of Maya src file	
	FSMakeFSSpec(0,0, mayaFile, &mayaSpec);			// get FSSpec to the src file
	
	
		/* CHANGE THE NAME FOR BG3D EXTENSION */
				
	for (i = mayaSpec.name[0]; i >= 1; i--)			// scan from the back looking for the "."
	{
		if (mayaSpec.name[i] == '.')				// put new extension here
		{
			i++;
			mayaSpec.name[i] = 'b';
			i++;
			mayaSpec.name[i] = 'g';
			i++;
			mayaSpec.name[i] = '3';
			i++;
			mayaSpec.name[i] = 'd';

			mayaSpec.name[0] = i;					// reset name length to here
				
			break;
		}
	}
	
	
				/* USE NAV SERVICES TO SPECIFY FILE */
				
	OpenLibResource();
	iErr = PutFileWithNavServices(&mayaSpec, &reply, &gExportSpec);
	CloseLibResource();
				
	return(iErr);	
}

#pragma mark -

/********************** OPEN RESOURCE ****************************/
//
// Opens and sets as active the plug-in file's rez fork
//

void OpenLibResource(void)
{
	if (gLibResRefNum == -1)							// see if already open
	{
		gRestoreResRefNum = CurResFile();						// get current rez so can restore later
	
		gLibResRefNum = FSpOpenResFile(&gSharedLibSpec, fsRdPerm);	// open this resource file
		if (gLibResRefNum != -1)
			UseResFile(gLibResRefNum);							// ...and use it
		else
			MayaDisplayError("OpenLibResource()  FSpOpenResFile failed!");
		
	}
}


/********************* CLOSE RESOURCE *****************************/
//
// stop using plug-in's rez fork and reset back to original 
//

void CloseLibResource(void)
{
	if (gLibResRefNum != -1)
	{
		CloseResFile(gLibResRefNum);
		gLibResRefNum = -1;
		UseResFile(gRestoreResRefNum);					// use the previous one		
	}
}

/**************** CONVERT FILE REPRESENTATION ******************/
//
// Coonverts URL paths from one type to another.  We primarily use it to convert
// UNIX file paths into HFS file paths.
//
// INPUT:	filename = the URL string
//			inStyle = the format of the input string (typically kCFURLPOSIXPathStyle)
//			outStyle = format that we wish to conver it to (typically kCFURLHFSPathStyle)
//

Boolean ConvertFileRepresentation (char *fileName, short inStyle, short outStyle)
{
CFStringRef rawPath;
CFURLRef baseURL;
CFStringRef newURL;
char newPath[500];

	if (fileName == nil)
		return (false);

	if (inStyle == outStyle)
		return (true);

	rawPath = CFStringCreateWithCString (nil, fileName, kCFStringEncodingUTF8);
	if (rawPath == nil)
		return (false);
	
	baseURL = CFURLCreateWithFileSystemPath (nil, rawPath, (CFURLPathStyle)inStyle, false);
	CFRelease (rawPath);
	if (baseURL == nil)
		return (false);
	
	newURL = CFURLCopyFileSystemPath (baseURL, (CFURLPathStyle)outStyle);
	CFRelease (baseURL);
	if (newURL == nil)
		return (false);

	CFStringGetCString (newURL, newPath, MAXPATHLEN, kCFStringEncodingUTF8);
	CFRelease (newURL);
	strcpy (fileName, newPath);
	return (true);
}

#pragma mark -

/**************** DRAW PICTURE INTO GWORLD ***********************/
//
// Uses Quicktime to load any kind of picture format file and draws
// it into the GWorld
//
//
// INPUT: myFSSpec = spec of image file
//
// OUTPUT:	theGWorld = gworld contining the drawn image.
//

OSErr DrawPictureIntoGWorld(FSSpec *myFSSpec, GWorldPtr *theGWorld, short depth)
{
OSErr						iErr;
GraphicsImportComponent		gi;
Rect						r;
ComponentResult				result;
PixMapHandle 				hPixMap;
	

			/* PREP IMPORTER COMPONENT */
			
	result = GetGraphicsImporterForFile(myFSSpec, &gi);		// load importer for this image file
	if (result != noErr)
	{
		DoAlert("\pDrawPictureIntoGWorld: GetGraphicsImporterForFile failed!  You do not have Quicktime properly installed, reinstall Quicktime and do a FULL install.");
		return(result);
	}
	
	iErr = GraphicsImportGetBoundsRect(gi, &r);				// get dimensions of image
	if (iErr)
		return(iErr);


			/* MAKE GWORLD */
	
	iErr = NewGWorld(theGWorld, depth, &r, nil, nil, 0);					// try app mem

	if (depth == 32)
	{
		hPixMap = GetGWorldPixMap(*theGWorld);				// get gworld's pixmap
		(**hPixMap).cmpCount = 4;							// we want full 4-component argb (defaults to only rgb)
	}


			/* DRAW INTO THE GWORLD */
	
	DoLockPixels(*theGWorld);	
	GraphicsImportSetGWorld(gi, *theGWorld, nil);			// set the gworld to draw image into
	GraphicsImportSetQuality(gi,codecLosslessQuality);		// set import quality

	result = GraphicsImportDraw(gi);						// draw into gworld
	CloseComponent(gi);										// cleanup
	if (result != noErr)
	{
		DoAlert("\pDrawPictureIntoGWorld: GraphicsImportDraw failed!");
		ShowSystemErr(result);
		DisposeGWorld (*theGWorld);
		*theGWorld= nil;
		return(result);
	}
	return(noErr);
}


