//	A2PixInterface.c

#include "COffscreen.h"
#include "FSUtils.h"
#include "CDialogGetInfo.h"
#include "CFile.h"
#include "A2Pix_AE.h"
#include "A2PixInterface.h"

Boolean		IsA2PixRunning(Net_ProcRec *procRecP)
{
	OSErr			err = noErr;
	Net_ProcRec		procRec;
	
	if (procRecP == NULL) {
		procRecP = &procRec;
	}
	
	err = Net_GetProcess('APPL', A2Pix_Creator, procRecP);

	return err == noErr;
}

COffscreen	*Convert_A2Pix2Coffs(Net_ProcRec *procRecP, Handle mainH, Handle auxH)
{
	COffscreen			*coffsP		= NULL;
	CDialogGetInfo		*getInfoP	= GetGetInfo();
	
	ASSERT(getInfoP);
	
	if (getInfoP) {
		PicHandle		a2PictH	= A2PixConvert(&procRecP->infoRec.processNumber, mainH, auxH);

		if (a2PictH) {
			TrackHandle((Handle)a2PictH, "a2pix picH", GetHandleSize((Handle)a2PictH));

			coffsP = GetNewCOffscreen(
				getInfoP->GetGrafPtr(), 
				32, getInfoP->CB_S_GetInfo_Offs, 
				getInfoP);

			if (coffsP) {
				Rect			dstR	= coffsP->GetFrame();

				coffsP->Use();
				HLock((Handle)a2PictH);
				DrawPicture(a2PictH, &dstR);
				HUnlock((Handle)a2PictH);
				coffsP->StopUsing();
			}

			TrackDisposeHandle((Handle)a2PictH);
		}
	}
	
	return coffsP;
}

CFile		*g_fileP = NULL;
void		SetPendingA2PixConvert(CFile *fileP)
{
	if (!g_fileP) {	//	no pending launch
		OSErr		err = noErr;		
		FSSpec		tempFSp;
		
		err = FSpCreateTempFile(
			kOnUserDisk, 
			"\pempty.dhgr", 
			A2Pix_Creator, 
			A2Pix_FileType1, 
			&tempFSp);
		
		if (!err) err = FSpLaunchInFinder(&tempFSp);
		
		if (err) ReportOSErr(err);
	}

	g_fileP = fileP;
}

void		HandlePendingA2PixConvert(void)
{
	if (g_fileP) {
		CDialogGetInfo		*getInfoP = GetGetInfo();
		
		if (getInfoP && getInfoP->i_entryP == g_fileP) {
			if (IsA2PixRunning()) {
				OSErr				err;
				ProcessSerialNumber	appPSN;
				
				err = GetCurrentProcess(&appPSN);
				if (!err) err = SetFrontProcess(&appPSN);
				if (err) ReportOSErr(err);

				getInfoP->InvalDialogItem(ADFS_GetInfo_USER_PREVIEW);
				getInfoP->ClearPreviewRec();
				g_fileP = NULL;
			}
		} else {
			g_fileP = NULL;
		}
	}
}

