/**
 * strings.cpp: Useful functions for manipulating strings
 **/
#include "core/strings.h"
#include <algorithm>
#include <cctype>
#include <locale>
#include <string>
#include <vector>

namespace Strings {

std::string Implode(const std::vector<std::string>& vector, const std::string& delimiter) {
	if (vector.size() < 1)
		return "-";
	std::string out = "";
	for (unsigned long long i = 0; i < vector.size(); i++) {
		out.append(vector.at(i));
		if (i < vector.size() - 1)
			out.append(delimiter);
	}
	return out;
}

std::string ReplaceAll(const std::string& string, const std::string& find, const std::string& replace) {
	std::string result;
	size_t pos, find_len = find.size(), from = 0;
	while ((pos = string.find(find, from)) != std::string::npos) {
		result.append(string, from, pos - from);
		result.append(replace);
		from = pos + find_len;
	}
	result.append(string, from, std::string::npos);
	return result;
}

/* this function probably fucks your RAM but whatevs */
std::string SanitizeLineEndings(const std::string& string) {
	std::string result(string);
	result = ReplaceAll(result, "\r\n", "\n");
	result = ReplaceAll(result, "<br>", "\n");
	result = ReplaceAll(result, "\n\n\n", "\n\n");
	return result;
}

std::string RemoveHtmlTags(const std::string& string) {
	std::string html(string);
	while (html.find("<") != std::string::npos) {
		auto startpos = html.find("<");
		auto endpos = html.find(">") + 1;

		if (endpos != std::string::npos) {
			html.erase(startpos, endpos - startpos);
		}
	}
	return html;
}

std::string TextifySynopsis(const std::string& string) {
	return RemoveHtmlTags(SanitizeLineEndings(string));
}

/* these functions suck for i18n!...
   but we only use them with JSON
   stuff anyway */
std::string ToUpper(const std::string& string) {
	std::string result(string);
	std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c) { return std::toupper(c); });
	return result;
}

std::string ToLower(const std::string& string) {
	std::string result(string);
	std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c) { return std::tolower(c); });
	return result;
}

} // namespace Strings
