#ifndef UPDATEUIPACKAGEFILE_H
#define UPDATEUIPACKAGEFILE_H
#include <filesystem>
#include <fstream>
#include <string>

#include "ISXMr.h"

inline std::chrono::system_clock::time_point ParseEmbeddedTimestamp(const std::string &timestamp)
{
    std::tm tm = {};
    std::istringstream ss(timestamp);
    ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
    return std::chrono::system_clock::from_time_t(std::mktime(&tm));
}

inline void UpdateUIPackageFile(const std::string &fileName,
                                const char *data, const size_t size)
{
    constexpr size_t innerspacePathBufferLength = 255;
    char innerspacePathBuffer[innerspacePathBufferLength];
    const std::filesystem::path innerspacePath = pISInterface->GetInnerSpacePath(
        innerspacePathBuffer, innerspacePathBufferLength);
    const std::filesystem::path fullPath = innerspacePath / R"(scripts/mr/ui)" / fileName;

    if (fullPath.has_parent_path() && !exists(fullPath.parent_path()))
    {
        create_directories(fullPath.parent_path());
    }
    // if (std::filesystem::exists(fullPath))
    // {
    //     // const auto embeddedTimestamp = ParseEmbeddedTimestamp(lastModifiedTimestamp);
    //     const auto lastWriteTimestamp = std::filesystem::last_write_time(fullPath);
    //     const auto lastWriteTimepoint = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
    //         lastWriteTimestamp - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now());

    //     // if (lastWriteTimepoint >= embeddedTimestamp)
    //     // {
    //     //     return;
    //     // }
    // }

    std::ofstream file(fullPath, std::ios::binary);
    file.write(reinterpret_cast<const char *>(data), size);
}

#endif // UPDATEUIPACKAGEFILE_H
