#pragma once
#include <iostream>
#include <string>
#include <sys/file.h>			// for ::open, ::close

/** this value object can split path by directory, name and suffix.*/
class FilePath
{
	std::string m_path;
public:
	/** by default, this object is empty string like std::string. */
	FilePath()
    		:m_path("")
{
}

	/** construct by string.*/
	FilePath(std::string path)
    		:m_path(path)
{
}


	/** check if empty or not.*/
	bool isValid()const
    {
	return !m_path.empty();
}

	
	/** check the file exists or not.*/
	bool exists()const
    {
	int descriptor = ::open(m_path.c_str(), O_RDONLY);
	//::close(descriptor);
	return descriptor != -1;
}

	
	const char* c_str()const
{
	return m_path.c_str();
}
    
	operator std::string()const
    {
	return m_path;
}

    
	FilePath& operator=(std::string path)
    {
	m_path = path;
	return *this;
}

	/** insert operator.*/
	friend std::ostream& operator<<(std::ostream& os, const FilePath& rh)
    {
	os << rh.m_path;
	return os;
}

	
	/** get whole path.*/
	std::string to_s()const
    {
	return m_path;
}

	
	std::string fileName()const
    {
	unsigned pos = m_path.rfind("/");
	if (pos == std::string::npos){
		return m_path;
	} else {
		return m_path.substr(pos+1, std::string::npos);
	}
}

	std::string baseName()const
    {
	std::string file_name = fileName();
	unsigned pos = file_name.rfind(".");
	if (pos == std::string::npos){
		return file_name;
	} else {
		return file_name.substr(0, pos);
	}
}

	
	std::string suffix()const
    {
	unsigned pos = m_path.rfind(".");
	if (pos == std::string::npos){
		return "";
	} else {
		return m_path.substr(pos+1, std::string::npos);
	}
}

	void setSuffix(std::string str)
    {
	m_path =  directory() + baseName() + "." + str;
}

	
	std::string directory()const
    {
	unsigned pos = m_path.rfind("/");
	if (pos == std::string::npos){
		return "";
	} else {
		return m_path.substr(0, pos+1);
	}
}

	void setDirectory(std::string str)
    {
	if (str[str.length()-1] != '/'){
		str +="/";
	}
	m_path = str + fileName();
}

};
