#include "sopnamsp.h"
#include "pifilechomac.h"

string PathNameFromDirID(long dirID, short vRefNum);

string PIGetFileName(string dir);
string PIGetExistingFileName(string dir);

string PIGetFileName(string dir)
{
  StandardFileReply reply;
  
  
  string fName;
  int i = dir.rfind(':');
  if (i == string::npos)
    fName = dir;
  else if (i == dir.length())
    fName = "";
  else
    fName = dir.substr(i+1);
    
  LStr255 defaultName(fName.c_str());
  
  StandardPutFile("\pSave as:",defaultName,&reply);
  
  if (!reply.sfGood) return "";
  
  string directory = PathNameFromDirID(reply.sfFile.parID,reply.sfFile.vRefNum);
  p2cstr(reply.sfFile.name);
  
//  return directory + '/' + (char*)reply.sfFile.name;
  return directory + ':' + (char*)reply.sfFile.name;
}

string PIGetExistingFileName(string /*dir*/)
{
  StandardFileReply reply;
  SFTypeList typeList;
  
  StandardGetFile(NULL,-1,typeList,&reply);
  
  if (!reply.sfGood) return "";
  
  string directory = PathNameFromDirID(reply.sfFile.parID,reply.sfFile.vRefNum);
  p2cstr(reply.sfFile.name);
  
//  return directory + '/' + (char*)reply.sfFile.name;
  return directory + ':' + (char*)reply.sfFile.name;
}


string PathNameFromDirID(long dirID, short vRefNum)
{
	DirInfo 	block;
	Str255		directoryName;
	OSErr		err;

	string fullPathName = "";

	block.ioDrParID = dirID;
	block.ioNamePtr = directoryName;
	do {
			block.ioVRefNum = vRefNum;
			block.ioFDirIndex = -1;
			block.ioDrDirID = block.ioDrParID;
			err = PBGetCatInfoSync(CInfoPBPtr(&block));
			p2cstr(directoryName);
			if (fullPathName != "") fullPathName = ':' + fullPathName;
			fullPathName =  ((char*)directoryName + fullPathName);
//			fullPathName = '/' + ((char*)directoryName + fullPathName);
	} while (block.ioDrDirID != 2);
	return fullPathName;
}


PIFileChooserMac::PIFileChooserMac(PIMsgHandler* par, char* nom, PIMessage msg)
: PIFileChooserGen(par, nom, msg)
{
  mAccNew = false;
  mFileName = "";
}

PIFileChooserMac::~PIFileChooserMac()
{}

void
PIFileChooserMac::Show()
{
  if (mAccNew)
    mFileName = PIGetFileName("");
  else
    mFileName = PIGetExistingFileName("");

// Envoyer un message....
  if (mFileName == "")
    Send(Msg(), PIMsg_Cancel, NULL);
  else
    Send(Msg(), PIMsg_OK, (void *) (GetFileName().c_str()));
}

void
PIFileChooserMac::AcceptNewFile(bool acc)
{
  mAccNew = acc;
}

void
PIFileChooserMac::SetPath(string const& /*path*/) {}
void
PIFileChooserMac::SetFileName(string const& /*fname*/) {}

string
PIFileChooserMac::GetPath()
{
  return "";
}

string
PIFileChooserMac::GetFileName()
{
  return mFileName;
}

