#include <unistd.h>
#include <iostream>
#include <cstring>
#include <filesystem>
#include <paths.hpp>

#ifdef _WIN32
#define READABLE(p)	_access(p.c_str(),R_OK)==0
#else
#define READABLE(p)	access(p.c_str(),R_OK)==0
#endif

std::string prefixConfig;	// directory to store config.toml in
std::string prefixCustom;	// directory for user-accessible models and cvdata
std::string prefixDefault;	// directory for pre-installed models and cvdata

void initPrefixes() {
#if defined (__gnu_linux__)
	prefixConfig = getenv("HOME") + std::string("/.config/facecam2d/");
	prefixCustom = getenv("HOME") + std::string("/.local/share/facecam2d/");
	prefixDefault = "/usr/share/facecam2d/";
#elif defined (__APPLE__)
	// config and supporting files are both stored in Library on MacOS
	prefixConfig = getenv("HOME") + std::string("/Library/Facecam2D/");
	prefixCustom = getenv("HOME") + std::string("/Library/Facecam2D/");
	prefixDefault = "/Applications/Facecam2D.app/";
#elif defined (_WIN32)
	prefixConfig = getenv("AppData") + std::string("\\Roaming\\Facecam2D\\");
	prefixCustom = getenv("AppData") + std::string("\\Local\\Facecam2D\\");
	prefixDefault = getenv("ProgramFiles") + std::string("\\Facecam2D\\");
#endif
}

void makePaths() {
	std::filesystem::create_directories(prefixConfig);
	std::filesystem::create_directories(prefixCustom + "models/");
	std::filesystem::create_directories(prefixCustom + "cvdata/");
}


std::string resolvePath(const char* path) {
	std::string customString	= prefixCustom + path;
	std::string defaultString	= prefixDefault + path;

	std::string result;

	if (READABLE(customString)) {
		result = customString;
	} else if (READABLE(defaultString)) {
		result = defaultString;
	} else {
		result = path;

		if(!(READABLE(std::string(path)))) {
			std::cerr << path << " not found!" << std::endl;
		}
	}

	return result;
}
