/*
 *  psychlops_io_file_OSX.cpp
 *  Psychlops Standard Library (MacOSX)
 *
 *  Last Modified 2006/01/05 by Kenchi HOSOKAWA
 *  (C) 2006 Kenchi HOSOKAWA, Kazushi MARUYA, Takao SATO
 */

#include <Carbon/Carbon.h>
#include <ApplicationServices/ApplicationServices.h>
#include <CoreServices/CoreServices.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>

#include <string>

#include "../../core/ApplicationInterfaces/psychlops_app.h"
#include "../../core/devices/psychlops_io_file.h"


namespace Psychlops {

	const char File::PATH_DEVIDER = '/';

	void File::initialize() {
		const int BUFSIZE = 1024;
		char *buf = new char[BUFSIZE];
		CFStringRef apppath = CFURLCopyFileSystemPath(CFBundleCopyBundleURL(CFBundleGetMainBundle()), kCFURLPOSIXPathStyle);
//		CFStringRef apppath = CFURLCopyPath(CFBundleCopyBundleURL(CFBundleGetMainBundle()));
		CFStringGetCString(apppath, buf, BUFSIZE, kCFStringEncodingUTF8);
		STANDARD_PATH[PATH_APP].path = buf;
		STANDARD_PATH[PATH_RSC].path = STANDARD_PATH[PATH_APP].path + "/Contents/Resources/";
		STANDARD_PATH[PATH_APP].path += "/../";
//		char * home = getenv("USER");
		CFStringRef username = CSCopyUserName(true);
		STANDARD_PATH[PATH_HOME].path = "/Users/";
		CFStringGetCString(username, buf, BUFSIZE, kCFStringEncodingUTF8);
		STANDARD_PATH[PATH_HOME].path += buf;
		STANDARD_PATH[PATH_HOME].path += "/";
		STANDARD_PATH[PATH_DOCUMENTS_ROOT].path = STANDARD_PATH[PATH_HOME].path + "Documents/";

		initialize_appname();

		setCurrentDirectoryDefault();
		delete buf;
	}

	void File::initialize_appname() {
		STANDARD_PATH[PATH_SETTING].path = STANDARD_PATH[PATH_HOME].path + "Library/" + AppInfo::appname + "/";
		STANDARD_PATH[PATH_DOCUMENTS].path = STANDARD_PATH[PATH_DOCUMENTS_ROOT].path + AppInfo::appname + "/";
		if(AppInfo::appname=="Psychlops" && AppInfo::expname!="") {
			STANDARD_PATH[PATH_SETTING].path += AppInfo::expname + "/";
			//STANDARD_PATH[PATH_DOCUMENTS].path += AppInfo::expname + "/";
		}
	}


	std::string File::getCurrentDirectory() {
		char buf[1024];
		if(getcwd(buf, 1024) == 0) Exception("failed to get current directory name.");
		return std::string(buf);
	}

	void File::setCurrentDirectory(const std::string &path, bool force_mkdir) {
		if(chdir(path.c_str()) && force_mkdir) {
			mkdir(path.c_str(), 0700);
			chdir(path.c_str());
		}
	}

	void File::setCurrentDirectoryDefault() {
		setCurrentDirectory(STANDARD_PATH[PATH_DOCUMENTS].path, true);
	}

	std::string File::replacePathDevider(const std::string &path) {
		std::string decoded_path = path;
		unsigned int found, restart;
		for(;;) {
			found=decoded_path.find('\\',restart);
			if(found==std::string::npos) { break; }
			decoded_path.replace(found, 1, 1, PATH_DEVIDER);
			restart = found;
		}
		return decoded_path;
	}


}	/*	<- namespace Psycholops 	*/
