//	CDirEntry.c

#include "MemUtils.h"
#include "COffscreen.h"
#include "ADFS_Prefs.h"
#include "Network.h"
#include "ProFileTypes.h"
#include "FSUtils.h"
#include "CCopyTree.h"
#include "ADFS_LogFile.h"
#include "CCopyFile_Tree.h"
#include "A2PixInterface.h"
#include "ADFS_Icons.h"
#include "CDialogCopy.h"
#include "ProStructs.h"
#include "ADFS_O_Callbacks.h"
#include "A2PixInterface.h"
#include "BasicTokenizer.h"

#include "CFolder.h"
#include "CFile.h"

OSErr		CFile::IFile(
	CDisk				*cDisk, 
	CFolder				*cParentFolder, 
	DiskLocSpecUnion	diskLoc, 
	EntryIndex			diskLocDirEntryIndex,	//	relative to cur dir sector
	EntryIndex			directoryIndex			//	relative to entire directory
) {
	OSErr			err = noErr;
	
	err = _inherited::IEntry(
		cDisk, 
		cParentFolder, 
		FSObject_FILE, 
		diskLoc, 
		diskLocDirEntryIndex, 
		directoryIndex);
		
	i_openingB = FALSE;
	
	if (!err) {
		SetBinFileType();
	}
	
	return err;
}

Err		CFile::EntryDispatchCB(
	O_CBType				cbType, 
	O_CBDataP			cbData)
{
	OSErr		err = noErr;
	
	switch (cbType) {
		
		case ADFS_O_CB_PANE_ARRAY_GET_FILES:
		case ADFS_O_CB_PANE_ARRAY_GET_FILES_FOLDERS:
		case ADFS_O_CB_PANE_ARRAY_GET_SEL_FILES_FOLDERS:
		case ADFS_O_CB_PANE_ARRAY_GET_SEL_FILES: {
			err = _inherited::EntryDispatchCB(
				ADFS_O_CB_PANE_ARRAY_GET, cbData);
			break;
		}
		
		default: {
			err = _inherited::EntryDispatchCB(cbType, cbData);
			break;
		}
	}

	return err;
}

ushort		CFile::GetLoadAddress(void)
{
	return 0;
}

void		CFile::SetLoadAddress(ushort address)
{
}

OSErr 		CFile::ReadFile(Byte *buffer, long length)
{
	OSErr	err = noErr;
	
	return err;
}

OSErr 		CFile::WriteFile(Byte *buffer, long length)
{
	OSErr	err = noErr;
	
	return err;
}

ADFS_IconType		CFile::GetIconType(void)
{
	ADFS_IconType	icons = 0;
	
//	if (IsDeleted()) {
//		icons = ADFS_Icon_UNDELETE;
//	} else 
	if (IsGraphic()) {
		icons = ADFS_Icon_PICT;
	} else if (IsTranslatable()) {
		icons = ADFS_Icon_TEXT;
	} else {
		icons = ADFS_Icon_DOCUMENT;
	}
	
	return icons;
}

#define		HAS_AUX(NAME)		(*((long *)(&(NAME[strlen(NAME) - 4]))) == '.AUX')

#define		ADD_AUX(NAME) {						\
	short _len = strlen(NAME);					\
	(*((long *)(&(NAME[_len]))) = '.AUX'); 	\
	NAME[_len + 4] = 0;	}
	
#define		STRIP_AUX(NAME)		(NAME[strlen(NAME) - 4] = 0)

void		CFile::SetBinFileType(void)
{
	switch (GetFileType_ProEquiv()) {
		
		case Pro_FileType_BAS: {
			i_fileType = ADFS_File_BASIC;
			break;
		}
		
		case Pro_FileType_INT: {
			i_fileType = ADFS_File_INTBASIC;
			break;
		}
		
		case Pro_FileType_TXT: {
			i_fileType = ADFS_File_TEXT;
			break;
		}
		
		case Pro_FileType_AWP: {
			i_fileType = ADFS_File_AWP;
			break;
		}
		
		case Pro_FileType_AWS: 
		case Pro_FileType_AWD: {
			i_fileType = ADFS_File_BINARY;
			break;
		}
		
		case Pro_FileType_BIN: {
			ushort		laddr;

			i_fileType = ADFS_File_BINARY;

			laddr	= GetLoadAddress();

			if (laddr == 0x2000 || laddr == 0x4000) {
				ushort	size	= GetLogicalSize();

				if (size > 0x1FF8 && size <= 0x2004) {
					char	buf[128];
					
					_inherited::GetName(buf);
					
					if (HAS_AUX(buf)) {
						i_fileType = ADFS_File_DHGR_BEAGLE;
					} else {
						i_fileType = ADFS_File_HGR;
					}
				} else if (size > 0x3FF8 && size <= 0x4004) {
					i_fileType = ADFS_File_DHGR_DAZ;
				}
			}
			break;
		}
		
		default: {
			i_fileType = ADFS_File_NONE;
			break;
		}
	}

	GetLogicalSize();
	
	i_eof = i_logical_sizeL;
}

void		CFile::CopyFileTextToClipboard(void)
{
	Handle		scrapH = CopyFileToHandle();
	
	if (scrapH) {
		ScrapRef	curScrap;

		ClearCurrentScrap();
		GetCurrentScrap(&curScrap);

		HLock(scrapH);
		
		PutScrapFlavor(
			curScrap, 'TEXT', 
			kScrapFlavorMaskNone, 
			GetHandleSize(scrapH), 
			*scrapH);
		
		HUnlock(scrapH);

		TrackDisposeHandle(scrapH);
	}
}


COffscreen		*CFile::CopyFilePicToCOffs(void)
{
	Net_ProcRec		procRec;
	COffscreen		*coffsP	= NULL;
	
	if (IsA2PixRunning(&procRec)) {
		Handle		mainH	= CopyFileToHandle(FALSE);
		Handle		auxH	= NULL;
//		Boolean		gotItB	= FALSE;
		
		if (mainH) {
			if (i_fileType == ADFS_File_DHGR_DAZ) {
				//	all set both pages in 1
			} else {
				char		bufAC[128];
				Boolean		swapB = FALSE;
				CEntry		*entryP = NULL;
				
				_inherited::GetName(bufAC);
				
				if (HAS_AUX(bufAC)) {
					STRIP_AUX(bufAC);
					swapB = TRUE;
				} else {
					ADD_AUX(bufAC);
				}
				
				entryP = GetParentFolder()->FindByName_C(bufAC);
				
				if (entryP && entryP->i_type == FSObject_FILE) {
					auxH = ((CFile *)entryP)->CopyFileToHandle();

					if (swapB) {
						Handle		tempH = mainH;
						
						mainH	= auxH;
						auxH	= tempH;
					}
					
					//	all set, 2 pages
				} else {
					//	all set 1 page
				}
			}
			
			coffsP = Convert_A2Pix2Coffs(&procRec, mainH, auxH);
			
			TrackDisposeHandle(mainH);
			if (auxH) TrackDisposeHandle(auxH);
			
			if (coffsP == NULL) {
				i_badPicB = TRUE;
			}
		}
	} else {
		SetPendingA2PixConvert(this);
	}
		
	return coffsP;
}

Handle		CFile::CopyFileToHandle(Boolean translateB)
{
	Handle		scrapH		= NULL;
	OSErr		err			= noErr;
	CCopyTree	*copyDestP	= NULL;
	CCopyTree	*copyTreeP	= NULL;

	if (!err) err = GetNewCopyTree(
		CCT_Copy_ENTRY, (Ptr)GetParent(), &copyDestP);
		
	if (!err) err = GetNewCopyTree(
		CCT_Copy_META_TREE, (Ptr)copyDestP, &copyTreeP);
	
	if (!err) {
		if (!err) err = copyTreeP->AddEntry(
			NULL, CCT_Copy_ENTRY, 
			(Ptr)this, NULL);
		
		SetCopyTranslated(translateB);
		if (!err) err = copyTreeP->Copy(FALSE);
		SetCopyTranslated((**gPrefsH).detokenizeB);

		copyTreeP->Dispose();
		copyTreeP = NULL;
	}
	
	if (!err) {
		CCT_MemFileRecH		fileRecH = ((CCopyFile_Tree *)
			copyDestP->i_sourceP)->GetFileRecH();

		scrapH				= (**fileRecH).dataH;
		(**fileRecH).dataH	= NULL;
	}
	
	if (copyDestP) copyDestP->Dispose();

	return scrapH;
}

long		CFile::GetFirstBufOffset(void)
{
	return 0;
}

void			CFile::SetFileAndAuxType(Byte fileType, ushort auxType)
{
	SetBinFileType();

	InvalStat(ADFS_Stat_ICON);
	InvalStat(ADFS_Stat_KIND);
}

void		CFile::GetPreview(ADFS_PreviewRec *previewRecP)
{
	_inherited::GetPreview(previewRecP);
	
	if (!i_badPicB) {
		if (IsTranslatable()) {
			previewRecP->u.textH = CopyFileToHandle();
			
			if (previewRecP->u.textH) {
				previewRecP->type = ADFS_Preview_TEXT;
			} else {
				i_badPicB = TRUE;
			}
		} else if (IsGraphic()) {
			previewRecP->u.offsP = CopyFilePicToCOffs();
			
			if (previewRecP->u.offsP) {
				previewRecP->type = ADFS_Preview_PIC;
			} else if (!i_badPicB) {
				previewRecP->u.textH = GetResource('TEXT', 128);

				if (previewRecP->u.textH) {
					TrackDetachResource("a2pix text resource", previewRecP->u.textH);
					previewRecP->type = ADFS_Preview_TEXT;
				}
			}
		}
	}
}


void		CFile::Open(void)
{
	if (IsTranslatable() || IsGraphic()) {
		FSSpec				folderSpec, tempFileSpec;
		char				nameAC[256];
		unsigned char 		*nameP		= (unsigned char *)&nameAC;
		OSErr				err			= noErr;
		CCopyTree			*copyTreeP	= NULL;
		Boolean				strippedB	= FALSE;
		RgnHandle			rgnH		= NewRgn();		

		_inherited::GetName(nameAC);
		ADFS_Log("Opening the file '");
		ADFS_Log(nameAC);
		ADFS_Log("'\n");

		if (rgnH) {
			Rect	srcR, dstR = GetEnclosingWindow()->GetWindowRect(WindowRect_INTERIOR);
			Point	thePoint = { 0, 0 };
						
			GetNameAndIconRgn(rgnH);
			GlobalToLocal(&thePoint);
			OffsetRgn(rgnH, thePoint.h, thePoint.v);

			GetRegionBounds(rgnH, &srcR);
			
			#ifndef __68k__
				PlayThemeSound(kThemeSoundLaunchApp);
			#endif
			
			ADFS_Log("ZoomRecting\n");
			ZoomRect(&srcR, &dstR);
		}

		
		if (IsGraphic()) {
			if (HAS_AUX(nameAC)) {
				STRIP_AUX(nameAC);
				strippedB = TRUE;
			}
		}

		CopyCStringToPascal(nameAC, nameP);
		
		if (!err) err = FSpCreateTempFile(
			kOnUserDisk, 
			nameP, 
			GetAppCreator(), 
			kFirstMagicBusyFiletype, 
			&tempFileSpec);

		if (!err) {
			ADFS_Log("getting parent folder of new temp file (should be temp items folder)\n");
			err = FSpGetParentFolder(
				&tempFileSpec, &folderSpec);
		}
		
		if (err) ReportOSErr(err);
		
		if (!err) {
			ADFS_Log("creating copy tree\n");
			err = GetNewCopyTree(
				CCT_Copy_FSSPEC, (Ptr)&folderSpec, &copyTreeP);
		}
		
		if (!err) {
			ADFS_Log("adding this entry to copy tree\n");
			err = copyTreeP->AddEntry(
				NULL, CCT_Copy_ENTRY, 
				(Ptr)this, NULL);
			
			if (!err && IsGraphic()) {
				CEntry		*entryP = NULL;
				
				CopyPascalStringToC(nameP, nameAC);

				if (!strippedB) {
					ADD_AUX(nameAC);
				}
				
				entryP = GetParentFolder()->FindByName_C(nameAC);
				
				if (entryP && entryP->i_type == FSObject_FILE) {
					err = copyTreeP->AddEntry(
						NULL, CCT_Copy_ENTRY, 
						(Ptr)entryP, NULL);
				}
			}

			if (!err) {
				i_openingB = TRUE;
				
				if (IsTranslatable()) {
					SetCopyTranslated(TRUE);
				}

				ADFS_Log("now copying file\n");
				err = copyTreeP->Copy(FALSE);

				SetCopyTranslated((**gPrefsH).detokenizeB);
				i_openingB = FALSE;
			}

			copyTreeP->Dispose();
			copyTreeP = NULL;
		}
		
		if (!err) {
			ADFS_Log("launching file\n");
			err = FSpLaunchInFinder(&tempFileSpec);
			if (err) ReportOSErr(err);
		}	
	}
}

void			CFile::GetAccessBits(Gen_AccessBits *bits)
{
	extern	Gen_AccessBits		Gen_kAccess_LOCKED;

	if (i_openingB) {
		*bits = Gen_kAccess_LOCKED;
	} else {
		_inherited::GetAccessBits(bits);
	}
}

