
#include <WFX/io/File.h>

#include <WFX/lang/WFXSystem.h>
#include <WFX/lang/WFXException.h>
#include <WFX/util/StringUtils.h>

using namespace WFX;
using namespace WFX::lang;
using namespace WFX::io;
using namespace WFX::util;
using namespace std;


File::File(string path) {
    Path = toAbsolutePath(path);
}

bool File::isDirectory() const {
    //TODO: yes ;)
    return false;
}

bool File::isFile() const {
    struct stat tagStat;
    return !stat(Path.c_str(), &tagStat);
}

string File::toAbsolutePath(string p) {
    string t;
    if (p[0]!='/') {
        //a relative path
        t = WFXSystem::getInstance().getCurrentPath();
        t += '/';
    }
    t += p;

    //check for relative tokens
    std::vector<std::string> tkns = StringUtils::tokenize(t, "/");
    std::list<std::string*> names;
    std::vector<std::string>::iterator it;
    for (it = tkns.begin(); it != tkns.end(); it++) {
        if ((*it) == ".")
            continue;
        else if ((*it) == ".." && names.size() != 0)
            names.pop_back();
        else
            names.push_back(&(*it));
    }
    //put together final string
    string r;
    std::list<std::string*>::iterator bla;
    for (bla = names.begin(); bla != names.end(); bla++) {
        r += "/";
        r += *(*bla);
    }
    
    return r;
}

string File::getExt() const {
    UInt pos = Path.find_last_of('.');
   
    if (pos == string::npos)
        THROW("No extension found in File: " << Path); 

    return Path.substr(++pos);
}

string File::getDir() const {
    UInt pos = Path.find_last_of('/');

    return Path.substr(0, pos);
}

std::string File::getPathPart(const std::string& pre) {
    string::size_type pos = Path.find_first_not_of(pre, 0); 
    return Path.substr(pos);
}


