/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "common/fs.hpp"

#include <filesystem>
#include <fstream>

#include "common/logger.hpp"

std::string polygun::utils::get_user_dir() {
#if defined(__APPLE__)
	// TODO
#elif defined(__unix__) // Linux etc
	char* c_data_home = getenv("XDG_DATA_HOME");
	std::string data_home;
	if(c_data_home) {
		data_home = std::string(c_data_home)+"/polygun";
		std::ofstream temp(data_home+"/a");
		if(temp.good())
			temp.close();
		else
			std::filesystem::create_directories(data_home);
		return data_home;
	}
	c_data_home = getenv("HOME");
	if(!c_data_home)
		LOG_FATAL("Failed to determine folder for writing user data (HOME or XDG_DATA_HOME not set)");
	data_home = std::string(c_data_home)+"/.polygun";
	std::ofstream temp(data_home+"/a");
	if(temp.good())
		temp.close();
	else
		std::filesystem::create_directories(data_home);
	return data_home;
#elif defined(_WIN32)
	char* c_appdata = getenv("appdata");
	std::string appdata;
	if(!c_appdata)
		LOG_FATAL("Failed to determine folder for writing user data (appdata not set)");
	appdata = std::string(c_appdata)+"/polygun";
	std::ofstream temp(appdata+"/a");
	if(temp.good())
		temp.close();
	else
		std::filesystem::create_directories(appdata);
	return appdata;
#else
	LOG_FATAL("polygun::utils::get_user_dir is not implemented for your platform");
	return "";
#endif
}
