#include "StringUtils.h"

#include <algorithm>
#include <sstream>

namespace VWeb {

static void StringLeftTrim(std::string &s) {
  s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
            return !std::isspace(ch);
          }));
}

static void StringRightTrim(std::string &s) {
  s.erase(std::find_if(s.rbegin(), s.rend(),
                       [](unsigned char ch) { return !std::isspace(ch); })
              .base(),
          s.end());
}

std::vector<std::string> String::Split(const std::string &s,
                                       const std::string &delimiter) {
  size_t pos_start = 0, pos_end, delim_len = delimiter.length();
  std::string token;
  std::vector<std::string> res;

  while ((pos_end = s.find(delimiter, pos_start)) != std::string::npos) {
    token = s.substr(pos_start, pos_end - pos_start);
    pos_start = pos_end + delim_len;
    res.push_back(token);
  }

  res.push_back(s.substr(pos_start));
  return res;
}
int String::ToNumber(std::string &string, int def) {
  char *pEnd;
  long val = std::strtol(string.c_str(), &pEnd, 10);
  if (pEnd == string)
    return def;
  return (int)val;
}

std::string String::Join(const std::vector<std::string> &items,
                         const std::string &delimiter) {
  std::stringstream string;
  for (size_t i = 0; i < items.size(); ++i) {
    if (i != 0)
      string << delimiter;
    string << items[i];
  }
  return string.str();
}

void String::Trim(std::string &value) {
  StringLeftTrim(value);
  StringRightTrim(value);
}
std::string String::TrimCopy(const std::string &value) {
  auto val = value;
  Trim(val);
  return val;
}

void String::ToLowerCase(std::string &value) {
  std::transform(value.begin(), value.end(), value.begin(),
                 [](unsigned char c) { return std::tolower(c); });
}
std::string String::UrlDecode(const std::string &val) {
  std::string ret;
  char ch;
  size_t i;
  unsigned int ii;
  for (i = 0; i < val.length(); i++) {
    if (int(val[i]) == 37) {
      char *pEnd;
      ii = std::strtoul(val.substr(i + 1, 2).c_str(), &pEnd, 16);
      ch = static_cast<char>(ii);
      ret += ch;
      i = i + 2;
    } else
      ret += val[i];
  }
  return (ret);
}
} // namespace VWeb