#include "pch.h"
#include "platform_legacy/legacy_platform_state.h"
#include "platform_api/platform_policy.h"

void webgl_pick_file_save(
    const std::string& path,
    const std::string& name,
    std::function<void(bool)> callback);
void webgl_sync();

namespace pp::platform::legacy {
namespace {

class RetainedWebPlatformServices final : public pp::platform::WebPlatformServices {
public:
    void publish_exported_image(std::string_view path) override
    {
        (void)path;
    }

    void flush_persistent_storage() override
    {
#ifdef __WEB__
        webgl_sync();
#endif
    }

    [[nodiscard]] int default_canvas_resolution() override
    {
        return pp::platform::platform_default_canvas_resolution(pp::platform::PlatformFamily::webgl);
    }

    void save_prepared_file(
        std::string_view path,
        std::string_view suggested_name,
        pp::platform::PreparedFileCallback callback) override
    {
        const std::string value(path);
        const std::string name(suggested_name);
#ifdef __WEB__
        webgl_pick_file_save(value, name, [callback = std::move(callback), value](bool success) {
            callback(value, success);
        });
#else
        (void)name;
        callback(value, false);
#endif
    }
};

}

[[nodiscard]] std::unique_ptr<pp::platform::WebPlatformServices> create_legacy_web_platform_services()
{
    return std::make_unique<RetainedWebPlatformServices>();
}

}
