/*
 *  psychlops_io_file.cpp
 *  Psychlops Standard Library (Universal)
 *
 *  Last Modified 2006/10/10 by Kenchi HOSOKAWA
 *  (C) 2006 Kenchi HOSOKAWA, Kazushi MARUYA and Takao SATO
 */


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

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

namespace Psychlops {

	File::PATH_ID_STRING::PATH_ID_STRING(const char * id_str) : id_string(id_str), id_string_length(id_string.length()) {};
	File::PATH_ID_STRING File::STANDARD_PATH[6] = {"%APP%", "%RESOURCES%", "%USER_HOME%", "%USER_SETTING%", "%USER_DOCUMENTS%", "%USER_DOCUMENTS_ROOT%"};

	bool File::appname_initialized = false;

	std::string File::decodePath(const char * path) {
		return decodePath(std::string(path));
	}
	std::string File::decodePath(const std::string &path) {
//		const int PROHOBITED_CNT = 9;
//		const char PROHOBITED[PROHOBITED_CNT] = {';',',',':','*','?','\"','<','>','|'};
		const int PROHOBITED_CNT = 7;
		const char PROHOBITED[PROHOBITED_CNT] = {';',',','*','?','<','>','|'};
		std::string decoded_path("");
		decoded_path.append(path);
		unsigned int loc;

		initialize_appname();

		decoded_path = replacePathDevider(decoded_path);

		for(int i=0; i<PROHOBITED_CNT; i++) {
			for(;;) {
				loc=decoded_path.find(PROHOBITED[i],0);
				if(loc==std::string::npos) { break; }
				decoded_path.erase(loc, 1);
			}
		}
		for(int i=0; i<6; i++) {
			loc=decoded_path.find(STANDARD_PATH[i].id_string,0);
			if(loc!=std::string::npos) {
				decoded_path.replace(loc, STANDARD_PATH[i].id_string_length, STANDARD_PATH[i].path);
			}
		}

		char filenametimestamp[64];
		time_t nowtime;
		time(&nowtime);
		strftime( filenametimestamp, 64, "%Y%m%d_%H%M%S", localtime(&nowtime) );
		for(;;) {
			loc = decoded_path.find( "%TIME_", 0 );
			if(loc==std::string::npos) { break; }
			decoded_path.erase(loc, 6);
			decoded_path.insert(loc,filenametimestamp);
		};
		for(;;) {
			loc = decoded_path.find( "%EXPNAME_", 0 );
			if(loc==std::string::npos) { break; }
			decoded_path.erase(loc, 9);
			decoded_path.insert(loc,AppInfo::expname);
		};

		return decoded_path;
	}



}	/*	<- namespace Psycholops 	*/
