
#include <WFX/util/StringUtils.h>

using namespace WFX;
using namespace WFX::util;
using namespace WFX::math;
using namespace std;

std::vector<string> StringUtils::tokenize(std::string str, std::string del) {
    std::vector<std::string> tokens;

    //skip delimiters at beginning
    string::size_type lastPos = str.find_first_not_of(del, 0);
    // Find first "non-delimiter"
    string::size_type pos = str.find_first_of(del, lastPos);
    while (string::npos != pos || string::npos != lastPos) {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(del, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(del, lastPos);
    }


    return tokens;
}

Real StringUtils::toReal(std::string str) {
    stringstream ss(str);

    Real r;
    ss >> r;

    return r;
}

Int StringUtils::toInt(std::string str) {
    stringstream ss(str);

    Int r;
    ss >> r;

    return r;
}

UInt StringUtils::toUInt(std::string str) {
    stringstream ss(str);

    UInt r;
    ss >> r;

    return r;
}

void StringUtils::parseIntV(const std::string& s, std::vector<Int>& v) {

    std::vector<std::string> sv = StringUtils::tokenize(s,",");

    //I hate it...
    if (sv.size() < 2) {
        sv = StringUtils::tokenize(s," ");
    }

    std::vector<std::string>::iterator it;
    for (it=sv.begin(); it!=sv.end(); it++) {
        v.push_back(StringUtils::toInt(*it));
    }

}


void StringUtils::parseRealV(const std::string& s, std::vector<Real>& v) {

    std::vector<std::string> sv = StringUtils::tokenize(s,",");

    //I hate it...
    if (sv.size() < 2) {
        sv = StringUtils::tokenize(s," ");
    }

    std::vector<std::string>::iterator it;
    for (it=sv.begin(); it!=sv.end(); it++) {
        v.push_back(StringUtils::toReal(*it));
    }

}

void StringUtils::parseVector3V(const std::string& s, std::vector<Vector3>& v) {
    std::vector<Real> rv;
    StringUtils::parseRealV(s, rv);

    Int vcount = rv.size();
    vcount = (vcount - (vcount%3))/3;

    for (int i=0; i<vcount; i++) {
        int k = i*3;
        Vector3 vec(rv[k], rv[k+1], rv[k+2]);
        v.push_back(vec);
    }
    
}

void StringUtils::parseCSVVector3V(const std::string& s, std::vector<Vector3>& v) {

    std::vector<std::string> sv = StringUtils::tokenize(s,",");

    std::vector<std::string>::iterator it;
    for (it=sv.begin(); it!=sv.end(); it++) {
        Vector3 vec;
        vec.parseStr(*it);
        v.push_back(vec);
    }


}

