#include "PathHelper.hpp"

#include <filesystem>
#include <cstdlib>

#ifdef _WIN32
    #include <windows.h>
    #include <shlobj.h>  // SHGetFolderPath
    #pragma comment(lib, "shell32.lib")
#else
    #include <unistd.h>
    #include <sys/types.h>
    #include <pwd.h>
#endif

bool TSE::FileExists(const std::string &path)
{
    return std::filesystem::exists(path);
}

void TSE::OpenFileReading(std::ifstream &stream, const std::string &path)
{
    stream.open(path, std::ios::in);
}

void TSE::CreateFileWriting(std::ofstream &stream, const std::string &path)
{
    stream.open(path, std::ios::out);
}

void TSE::AppendFileWriting(std::ofstream &stream, const std::string &path)
{
    stream.open(path, std::ios::app);
}

void TSE::GetAppDataPath(std::string &path)
{
    #ifdef _WIN32
    char appDataPath[MAX_PATH];
    if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_APPDATA, nullptr, 0, appDataPath))) {
        path = std::string(appDataPath) + "\\TSE";
    } else {
        path = ".\\TSE"; // fallback
    }
#else
    const char* homeDir = getenv("HOME");
    if (!homeDir) {
        struct passwd* pw = getpwuid(getuid());
        homeDir = pw->pw_dir;
    }
    path = std::string(homeDir) + "/.local/share/TSE";
#endif
    if(!FileExists(path)){
        std::filesystem::create_directory(path);
    }
}

void TSE::CombinePaths(std::string &res, const std::string &path1, const std::string &path2)
{

    #ifdef _WIN32
    //check for path parts containing forwardlasches
    res = path1 + "\\" + path2;
    #else
    //check for path parts containing backslasches
    res = path1 + "/" + path2;
    #endif
}
