#include "pch.h"
#include "platform_legacy/legacy_platform_services.h"

#include <memory>

#include "legacy_ui_gl_dispatch.h"
#include "log.h"
#include "platform_api/network_tls_policy.h"
#include "platform_api/platform_policy.h"
#include "renderer_gl/opengl_capabilities.h"

#ifdef __LINUX__
#include <tinyfiledialogs.h>
#include "platform_linux/linux_platform_services.h"
std::string linux_home_path();
int mkpath(const std::string& dir, mode_t mode = DEFFILEMODE);
#elif __WEB__
void webgl_pick_file(std::function<void(std::string)> callback);
void webgl_pick_file_save(
    const std::string& path,
    const std::string& name,
    std::function<void(bool)> callback);
void webgl_sync();
#endif

namespace {

// DEBT-0017: retained non-Windows fallback adapter until each platform owns a
// concrete PlatformServices implementation without this bridge.
class LegacyPlatformServices final : public pp::platform::PlatformServices {
public:
    explicit LegacyPlatformServices(pp::platform::legacy::LegacyPlatformServicesConfig config = {})
        : glfw_shell_(std::move(config.glfw_shell))
        , web_platform_services_(config.web_platform_services)
    {
    }

    [[nodiscard]] pp::platform::PlatformStoragePaths prepare_storage_paths() override
    {
#if __LINUX__
        const std::string data_path = linux_home_path() + "/PanoPainter";
        mkpath(data_path + "/brushes");
        mkpath(data_path + "/brushes/thumbs");
        mkpath(data_path + "/patterns");
        mkpath(data_path + "/patterns/thumbs");
        mkpath(data_path + "/settings");
        mkpath(data_path + "/frames");
        return {
            data_path,
            data_path,
            data_path + "/frames",
            {},
        };
#elif __WEB__
        const std::string data_path = "/PanoPainter";
        mkdir(data_path.c_str(), 0777);
        mkdir((data_path + "/brushes").c_str(), 0777);
        mkdir((data_path + "/brushes/thumbs").c_str(), 0777);
        mkdir((data_path + "/patterns").c_str(), 0777);
        mkdir((data_path + "/patterns/thumbs").c_str(), 0777);
        mkdir((data_path + "/settings").c_str(), 0777);
        mkdir((data_path + "/frames").c_str(), 0777);
        return {
            data_path,
            data_path,
            data_path + "/frames",
            {},
        };
#else
        return {};
#endif
    }

    void log_stacktrace() override
    {
    }

    void trigger_crash_test() override
    {
    }

    [[nodiscard]] std::string clipboard_text() override
    {
        return {};
    }

    [[nodiscard]] bool set_clipboard_text(std::string_view text) override
    {
        const std::string value(text);
        (void)value;
        return false;
    }

    void set_cursor_visible(bool visible) override
    {
        (void)visible;
    }

    void set_virtual_keyboard_visible(bool visible) override
    {
        (void)visible;
    }

    void attach_ui_thread() override
    {
    }

    void detach_ui_thread() override
    {
    }

    void acquire_render_context() override
    {
#if __LINUX__ || __WEB__
        invoke_legacy_glfw_shell_callback(glfw_shell_.acquire_render_context);
#endif
    }

    void release_render_context() override
    {
    }

    void present_render_context() override
    {
#if __LINUX__ || __WEB__
        invoke_legacy_glfw_shell_callback(glfw_shell_.present_render_context);
#endif
    }

    void bind_default_render_target() override
    {
        pp::legacy::ui_gl::bind_opengl_framebuffer(
            pp::renderer::gl::framebuffer_target(),
            pp::renderer::gl::default_framebuffer_id());
    }

    void bind_main_render_target() override
    {
        bind_default_render_target();
    }

    void apply_render_platform_hints() override
    {
    }

    void install_render_debug_callback() override
    {
    }

    void begin_render_capture_frame() override
    {
    }

    void end_render_capture_frame() override
    {
    }

    [[nodiscard]] bool deletes_recorded_files_on_clear() override
    {
        return pp::platform::platform_deletes_recorded_files_on_clear(
            pp::platform::current_platform_family());
    }

    void clear_recorded_files(std::string_view recording_path) override
    {
        (void)recording_path;
    }

    void publish_exported_image(std::string_view path) override
    {
        const auto family = pp::platform::current_platform_family();
        if (family == pp::platform::PlatformFamily::webgl)
        {
            active_web_platform_services().publish_exported_image(path);
            return;
        }
        if (!pp::platform::platform_publishes_exported_images(family))
        {
            (void)path;
            return;
        }
        (void)path;
    }

    void flush_persistent_storage() override
    {
        const auto family = pp::platform::current_platform_family();
        if (family == pp::platform::PlatformFamily::webgl)
        {
            active_web_platform_services().flush_persistent_storage();
            return;
        }
        if (!pp::platform::platform_flushes_persistent_storage(family))
            return;
    }

    [[nodiscard]] std::vector<std::string> document_browse_roots(
        std::string_view work_path,
        std::string_view data_path) override
    {
        return pp::platform::platform_document_browse_roots(
            pp::platform::current_platform_family(),
            work_path,
            data_path);
    }

    void save_ui_state() override
    {
        if (!pp::platform::platform_saves_native_ui_state(pp::platform::current_platform_family()))
            return;
    }

    [[nodiscard]] bool enables_live_asset_reloading() override
    {
        return pp::platform::platform_enables_live_asset_reloading(
            pp::platform::current_platform_family());
    }

    void update_platform_frame(float delta_time_seconds) override
    {
        (void)delta_time_seconds;
    }

    void report_rendered_frames(int frames) override
    {
#ifdef __LINUX__
        pp::platform::linux_desktop::report_rendered_frames(frames);
#else
        (void)frames;
#endif
    }

    void pick_image(pp::platform::PickedPathCallback callback) override
    {
#ifdef __LINUX__
        if (auto p = tinyfd_openFileDialog("Open File", "", 0, nullptr, nullptr, false))
            invoke_picked_path_if_selected(p, callback);
#elif __WEB__
        webgl_pick_file(callback);
#else
        (void)callback;
#endif
    }

    void pick_file(std::vector<std::string> file_types, pp::platform::PickedPathCallback callback) override
    {
#ifdef __LINUX__
        if (auto p = tinyfd_openFileDialog("Open File", "", 0, nullptr, nullptr, false))
            invoke_picked_path_if_selected(p, callback);
#elif __WEB__
        webgl_pick_file(callback);
#else
        (void)file_types;
        (void)callback;
#endif
    }

    void pick_save_file(std::vector<std::string> file_types, pp::platform::PickedPathCallback callback) override
    {
        (void)file_types;
        (void)callback;
    }

    void pick_directory(pp::platform::PickedPathCallback callback) override
    {
#ifdef __ANDROID__
        (void)callback;
#else
        (void)callback;
#endif
    }

    [[nodiscard]] bool supports_working_directory_picker() override
    {
        return pp::platform::platform_supports_working_directory_picker(
            pp::platform::current_platform_family());
    }

    [[nodiscard]] std::string format_working_directory_path(std::string_view path) override
    {
        return std::string(path);
    }

    [[nodiscard]] bool uses_prepared_file_writes() override
    {
        return pp::platform::platform_uses_prepared_file_writes(
            pp::platform::current_platform_family());
    }

    [[nodiscard]] bool uses_work_directory_document_export_collections() override
    {
        return pp::platform::platform_uses_work_directory_document_export_collections(
            pp::platform::current_platform_family());
    }

    [[nodiscard]] bool disables_network_tls_verification() override
    {
        return pp::platform::default_disables_network_tls_verification();
    }

    [[nodiscard]] bool uses_ppbr_export_data_directory_override() override
    {
        return pp::platform::platform_uses_ppbr_export_data_directory_override(
            pp::platform::current_platform_family());
    }

    [[nodiscard]] bool supports_sonarpen() override
    {
        return pp::platform::platform_supports_sonarpen(pp::platform::current_platform_family());
    }

    void start_sonarpen() override
    {
    }

    [[nodiscard]] int default_canvas_resolution() override
    {
        const auto family = pp::platform::current_platform_family();
        if (family == pp::platform::PlatformFamily::webgl)
            return active_web_platform_services().default_canvas_resolution();
        return pp::platform::platform_default_canvas_resolution(family);
    }

    [[nodiscard]] bool draws_canvas_tip_for_pointer(
        bool is_mouse,
        bool is_stylus,
        bool is_left_button_release) override
    {
        return pp::platform::platform_draws_canvas_tip_for_pointer(
            pp::platform::current_platform_family(),
            is_mouse,
            is_stylus,
            is_left_button_release);
    }

    [[nodiscard]] float adjust_canvas_input_pressure(float pressure) override
    {
        return pressure;
    }

    [[nodiscard]] pp::platform::PreparedFileTarget prepare_writable_file(
        std::string_view type,
        std::string_view default_name,
        std::string_view data_path,
        std::string_view temporary_path) override
    {
        return pp::platform::plan_platform_writable_file(
            pp::platform::current_platform_family(),
            type,
            default_name,
            data_path,
            temporary_path);
    }

    void display_file(std::string_view path) override
    {
        (void)path;
    }

    void share_file(std::string_view path) override
    {
        (void)path;
    }

    void request_app_close() override
    {
#ifdef __LINUX__
        invoke_legacy_glfw_shell_callback(glfw_shell_.request_app_close);
#endif
    }

    [[nodiscard]] bool start_vr_mode() override
    {
        return false;
    }

    void stop_vr_mode() override
    {
    }

    void save_prepared_file(
        std::string_view path,
        std::string_view suggested_name,
        pp::platform::PreparedFileCallback callback) override
    {
        const auto family = pp::platform::current_platform_family();
        if (family == pp::platform::PlatformFamily::webgl)
        {
            active_web_platform_services().save_prepared_file(
                path,
                suggested_name,
                std::move(callback));
            return;
        }

        const std::string value(path);
        const std::string name(suggested_name);
        (void)name;
        callback(value, false);
    }

private:
    [[nodiscard]] pp::platform::WebPlatformServices& active_web_platform_services() const noexcept
    {
        if (web_platform_services_)
            return *web_platform_services_;
        return pp::platform::active_web_platform_services();
    }

    static void invoke_legacy_glfw_shell_callback(const std::function<void()>& callback)
    {
        if (callback)
            callback();
    }

    pp::platform::legacy::LegacyGlfwPlatformShell glfw_shell_;
    pp::platform::WebPlatformServices* web_platform_services_ = nullptr;
};

}

namespace pp::platform::legacy {

std::unique_ptr<PlatformServices> create_platform_services(
    LegacyPlatformServicesConfig config)
{
    return std::make_unique<LegacyPlatformServices>(std::move(config));
}
}
