/*-----------------------------------------------
	GptFObj.CPP -- File Open, Save Dialog Boxes
	Class FileObject
  -----------------------------------------------*/

#include <windows.h>
#include "gpt.h"
#include <stdio.h>
//#include <stdarg.h>

FileObjectPt FileObject::ThisFileObject=NULL;


BOOL UpdateListBox(HWND, cStr FilePath, cStr FileSpec);



LPSTR lstrchr  (LPSTR str, char ch) ;
LPSTR lstrrchr (LPSTR str, char ch) ;

static char      szDefExt   [5]  ;
static char      szFileName [96] ;
static char      szFileSpec [16] ;
static WORD      wFileAttr, wStatus ;


BOOL FAR PASCAL _export FileObject::FileNewDlgProc(HWND hDlg, WORD message,
																WORD wParam, LONG lParam)
	  {
	  char  cLastChar ;
	  short nEditLen ;
	  char stg[255];
	  switch (message)  // handle WM_INITDIALOG, WMCOMMAND
		  {
		  case WM_INITDIALOG:
		  ThisFileObject= (FileObjectPt)GetObjectPt(lParam);
		  if (!UpdateListBox(hDlg, ThisFileObject->Path,
											ThisFileObject->Spec))  MessageBeep (0) ;
		  SetDlgItemText(hDlg,IDD_MESS, ThisFileObject->DialogMess);
		  return TRUE ;

		  case WM_COMMAND:
		  switch (wParam)   // control ID's IDD_FLIST, IDD_FNAME, IDOK, IDCANCEL
			  {
			  case IDD_FLIST:        // Something done with listbox
			  switch (HIWORD (lParam))   // Handles LBN_SELCHANGE, LBN_DBLCLK
				  {
				  case LBN_DBLCLK:
				  if ( FileObject::GetNewChoice(hDlg, CREATEFILE) )   // file selected and opened
					  EndDialog (hDlg, FILE_SELECTED);
				  return TRUE;

				  case LBN_SELCHANGE:   // listbox selection change
				  if (DlgDirSelect (hDlg, stg, IDD_FLIST))  // a path selected
						strcat(stg, ThisFileObject->Spec);              // append filename
				  SetDlgItemText (hDlg, IDD_FNAME, stg) ;
				  return TRUE ;
				  }   // End  switch (HIWORD (lParam))
			  break ;     // End case IDD_FLIST

			  case IDD_FNAME:
			  if (HIWORD (lParam) == EN_CHANGE) EnableWindow (
				 GetDlgItem (hDlg, IDOK), (BOOL) SendMessage (LOWORD (lParam),
															WM_GETTEXTLENGTH, 0, 0L)) ;
			  return TRUE ;

			  case IDOK:
			  if ( FileObject::GetNewChoice(hDlg, CREATEFILE))   // file selected and opened
					  EndDialog (hDlg, FILE_SELECTED);
			  return TRUE;
			  case IDCANCEL: EndDialog (hDlg, NO_FILE_SELECTED);  return TRUE ;
			  }   // End switch (wParam)
		  break; // End case WM_COMMAND
		  }      // end switch (message)
	  return FALSE ;
	  }

BOOL FAR PASCAL _export FileObject::FileOpenDlgProc (HWND hDlg, WORD message,
																WORD wParam, LONG lParam)
	  {
	  char  cLastChar ;
	  short nEditLen ;
	  char stg[255];
	  switch (message)  // handle WM_INITDIALOG, WMCOMMAND
		  {
		  case WM_INITDIALOG:
		  ThisFileObject= (FileObjectPt)GetObjectPt(lParam);
		  if (!UpdateListBox(hDlg, ThisFileObject->Path,
											ThisFileObject->Spec))  MessageBeep (0) ;
		  SetDlgItemText(hDlg,IDD_MESS, ThisFileObject->DialogMess);
		  return TRUE ;

		  case WM_COMMAND:
		  switch (wParam)   // control ID's IDD_FLIST, IDD_FNAME, IDOK, IDCANCEL
			  {
			  case IDD_FLIST:        // Something done with listbox
			  switch (HIWORD (lParam))   // Handles LBN_SELCHANGE, LBN_DBLCLK
				  {
				  case LBN_DBLCLK:
				  if ( FileObject::GetNewChoice(hDlg, READFILE) )   // file selected and opened
					  EndDialog (hDlg, FILE_SELECTED);
				  return TRUE;

				  case LBN_SELCHANGE:   // listbox selection change
				  if (DlgDirSelect (hDlg, stg, IDD_FLIST))  // a path selected
						strcat(stg, ThisFileObject->Spec);              // append filename
				  SetDlgItemText (hDlg, IDD_FNAME, stg) ;
				  return TRUE ;
				  }   // End  switch (HIWORD (lParam))
			  break ;     // End case IDD_FLIST

			  case IDD_FNAME:
			  if (HIWORD (lParam) == EN_CHANGE) EnableWindow (
				 GetDlgItem (hDlg, IDOK), (BOOL) SendMessage (LOWORD (lParam),
															WM_GETTEXTLENGTH, 0, 0L)) ;
			  return TRUE ;

			  case IDOK:
			  if ( FileObject::GetNewChoice(hDlg,READFILE))   // file selected and opened
					  EndDialog (hDlg, FILE_SELECTED);
			  return TRUE;
			  case IDCANCEL: EndDialog (hDlg, NO_FILE_SELECTED);  return TRUE ;
			  }   // End switch (wParam)
		  break; // End case WM_COMMAND
		  }      // end switch (message)
	  return FALSE ;
	  }

//  FileObject::DialogSetup - Setup Object variables for use in a dialog
void   FileObject::DialogFileSetup(cStr Mess, cStr Path, cStr Spec,	cStr Ext, WORD wAttr)
	{
	_fstrcpy( this->Path, Path);
	_fstrcpy(this->Spec, Spec);
	_fstrcpy(this->Ext, Ext);
	this->DialogMess = new char[_fstrlen(Mess) + 1];
	_fstrcpy(this->DialogMess, Mess);
	this->HFile = 0;
	this->wAttr = wAttr;
	}


//  FileObject::DialogFileInfo - Move static Setup Object variables to local
//                               FileObject
void   FileObject::DialogFileInfo()
	{
	//strcpy(LocalPath, StaticPath);
	//strcpy(LocalSpec, StaticSpec);
	//strcpy(LocalExt,  StaticExt);
	//LocalHFile = StaticHFile;
	}

//  FileObject::OpenRead - return TRUE if file opened for read
BOOL FileObject::OpenRead(  HWND hWndParent  )
	{
	DWORD lParam;
	FARPROC lpfnDlgProc = MakeProcInstance(
		  (FARPROC)FileObject::FileOpenDlgProc, Appl::hInstance) ;
	// Do dialog passing pointer to file object
	SetObjectPt(this, &lParam);
	int iReturn = DialogBoxParam ( Appl::hInstance, "FileOpen",  hWndParent,
						  lpfnDlgProc,lParam) ;
	FreeProcInstance(lpfnDlgProc);
	if (iReturn == FILE_SELECTED )
		{
		/* MessageBox(hWndParent, "New File Selected", "Dialog Result",
								  MB_ICONINFORMATION | MB_OK); */
		return TRUE;
		}
	else return FALSE;   // no file opened
	}
//  FileObject::OpenWrite - return TRUE if file opened for write
BOOL FileObject::OpenWrite(  HWND hWndParent  )
	{
	DWORD lParam;
	FARPROC lpfnFileDlgProc = MakeProcInstance(
		  (FARPROC)FileObject::FileNewDlgProc, Appl::hInstance) ;
	// Do dialog passing pointer to file object
	SetObjectPt(this, &lParam);
	int iReturn = DialogBoxParam ( Appl::hInstance, "FileOpen",  hWndParent,
						  lpfnFileDlgProc,lParam) ;
	FreeProcInstance(lpfnFileDlgProc);
	if (iReturn == FILE_SELECTED )
		{
		/* MessageBox(hWndParent, "New File Selected", "Dialog Result",
								  MB_ICONINFORMATION | MB_OK); */
		return TRUE;
		}
	else return FALSE;   // no file opened
	}

// **** UpdateListBox - use local path, filespec to update
//                      listbox, edit controls
BOOL UpdateListBox(HWND hDlg, cStr Path, cStr Spec)
	{
	char stg[255];
	BOOL NotWild;
	_fstrcpy(stg, Path);
	_fstrcat(stg, Spec);
	NotWild = FALSE;
	if (!lstrchr((LPSTR) stg,'*')  && !lstrchr  ((LPSTR) stg,'?') )
		{
		strcat(stg,"*");
		NotWild = TRUE;
		}
	if ( DlgDirList(hDlg, stg, IDD_FLIST,IDD_FPATH, 0X4010))
		{
		SendDlgItemMessage (hDlg, IDD_FNAME, EM_LIMITTEXT, 80, 0L) ;
		if (NotWild) stg[strlen(stg) - 1] = 0;
		SetDlgItemText(hDlg, IDD_FNAME, stg);
		SendDlgItemMessage(hDlg,IDD_FLIST,LB_SELECTSTRING,-1,
																  (long)(LPSTR)stg);
		return TRUE;
		}
	return FALSE;
	}

// ******* GetNewChoice()
// User has selected new directory or file
// Return True if valid file selected
BOOL FileObject::GetNewChoice(HWND hDlg, enum Modes FileAccess )
	{
	LPOFSTRUCT pof = &(ThisFileObject->OF);
	char EditName[255];
	int iret;
	iret = GetDlgItemText(hDlg, IDD_FNAME, EditName, 128);
	int nEditLen  = lstrlen ( EditName) ;
	char cLastChar = *AnsiPrev (EditName, EditName + nEditLen) ;

	if (cLastChar == '\\' || cLastChar == ':')
										  lstrcat (EditName, ThisFileObject->Spec) ;
	if (strchr(EditName,'*') || strchr(EditName,'?'))  // wildcardname
		{
		SeparateFile( (LPSTR)ThisFileObject->Path, (LPSTR)ThisFileObject->Spec,
				 (LPSTR)ThisFileObject->Ext, (LPSTR)EditName);
		if (!UpdateListBox(hDlg,ThisFileObject->Path,ThisFileObject->Spec))
																  MessageBeep(1);
		return FALSE;
		}
	// no wildcard  - a directory name ??

	EditName[iret] = '\\';   // make into directory name
	EditName[iret+1] = 0;
	// See if a directory
	if (UpdateListBox(hDlg, EditName,ThisFileObject->Spec)) return FALSE; // yes
	// assume a file and try to open
	EditName[iret] = 0;
	if ( FileAccess == READFILE)      // opening for read
		{
		iret = OpenFile (EditName, pof, OF_READ | OF_SHARE_DENY_WRITE );
		if (-1 != iret)
			{

			// opened file
			ThisFileObject->HFile = iret;
			GetDlgItemText(hDlg, IDD_FPATH, ThisFileObject->Path, 128);
			strcat(ThisFileObject->Path,"\\");
			strcpy(ThisFileObject->Spec, EditName);
			return TRUE;
			}
		// add extension in none already there
		if (!lstrchr ((LPSTR) EditName, '.') )
			{
			// no try to add and see if file exists
			lstrcat (EditName,ThisFileObject->Ext);
			if (-1 != OpenFile (EditName, pof, OF_EXIST )) // exists
				{
				SetDlgItemText(hDlg, IDD_FNAME, EditName);
				return FALSE; // make user verify
				}
			}
		MessageBeep(0) ;
		OKMsgBox( "Try Again", "** %s **", sys_errlist[pof->nErrCode]);
		return FALSE;
		}

	if ( FileAccess == CREATEFILE) // try opening for create/overwrite
		{
		iret = OpenFile (EditName, pof, OF_EXIST ); // See if would overwite
		if (-1 != iret)    // file exists
			{
			if (!OKCancelMsgBox( "Overwrite??"," %s Exists - Overwrite?",
										  EditName)) return FALSE;
		  //	iret = OpenFile(EditName, pof, OF_DELETE );
			iret = OpenFile(EditName, pof, OF_CREATE | OF_SHARE_EXCLUSIVE );
			if (-1 != iret)  { ThisFileObject->HFile = iret; return TRUE;  }
			else
				{
				OKMsgBox( "Open Failure","Could not Open %s for Write",EditName);
				return FALSE;
				}
			}
		else    // file does not exist - try to open
			{
			iret = OpenFile(EditName, pof, OF_CREATE | OF_SHARE_EXCLUSIVE );
			if (-1 != iret)  { ThisFileObject->HFile = iret; return TRUE;  }
			}
		MessageBeep(0) ;
		OKMsgBox( "Try Again", "** %s **", sys_errlist[pof->nErrCode]);
		return FALSE;
		}
	return FALSE;
	}

