// __author__ = Juan Carlos De Abreu (jcabreur@gmail.com)

/**
 * TODO(jcabreur): write a general comment here
 * General functions parse paths...
 */

#ifndef UTIL_FUNCS_H__
#define UTIL_FUNCS_H__

#include "../global.h"
#include "string.h"
//#include "../Includes/Basic.h"

BEGIN_TEG_NAMESPACE();

// TODO: change the name to this file ... maybe to utilities

// TODO: change to another file like a File that has the utilities function
// to manage the path of files

// Function to get path of a file without the name of the file
// for GetPathWithOutFileName("Data/Textures/wall.jpg") return "Data/Textures/"
inline std::tstring GetPathWithOutFileName(std::tstring path) {
  // Return the substring with the path
  return path.substr(0, path.rfind("/") + 1);
}

// 
// for example; path = "Data/Texture/wall.jpg" return "Data/Texture"
inline std::tstring GetPathWithOutLastSlash(std::tstring path) {
  return path.substr(0, path.rfind("/"));
}

//
// for example; path = "../Data/texture" return "Data/Texture"
inline std::tstring GetPathWithOutFirstSlash(std::tstring path) {
  return path.substr(path.find("/") + 1);
}

// Return the extension of a file.
// For example; path = "/Data/Model/home.obj" return "obj"
inline std::tstring GetExt(const std::tstring& path) {
  return path.substr(path.rfind(_T(".")) + 1);
}

// TODO: create a method to change al the \ for / in a path ...

// Return the fileName defined as "base name" + "file extension".
// For example; path = "/Data/Model/home.obj" return "home.obj"
inline std::tstring GetFileName(const std::tstring& path) {
  if (path.find(_T("/")) != -1) return path.substr(path.rfind(_T("/")) + 1);
  else return path.substr(path.rfind(_T("\\")) + 1);
}

// Return the base file name.
// For example; path = "/Data/Model/home.obj" return "home".
inline std::tstring GetBaseFileName(const std::tstring& path) {
  const std::tstring fileName = GetFileName(path);
  return fileName.substr(0, fileName.rfind(_T(".")));
}

// Function to get path for the origin of one ..
// for example; src = "Data/texture/wall.jpg" and dest = "../Model/home.obj"
//				return "Data/Model/home.obj"
inline std::tstring GetAPathFromOne(std::tstring src, std::tstring dest) {
  // Check if the source has file or is only a path.
  // So, remove the file name.
  if (src.find(".") != -1) src = GetPathWithOutLastSlash(src);

  // 
  while (dest.find("../") != -1) {
    dest = GetPathWithOutFirstSlash(dest);
    src = GetPathWithOutLastSlash(src);
  }

  // Return the path builded
  if (src.empty()) return dest;
  return src + std::tstring(_T("/")) + dest;
}


// Function to check if a file exist.
//   Return True if the file exist, otherwise false.
inline bool fileExist(const std::tstring& path) {
  FILE *f = fopen(path.c_str(), "r");
  if (f == NULL) return false;
  fclose(f); return true;
}

END_TEG_NAMESPACE();

#endif  // UTIL_FUNCS_H__
