#include "pch.h"
#include "app_core/command_convert.h"
#include "app.h"
#include "canvas.h"
#include "legacy_ui_gl_dispatch.h"
#include "log.h"
#include "renderer_gl/opengl_capabilities.h"

namespace {

void apply_convert_command_state()
{
    const auto status = pp::renderer::gl::apply_panopainter_convert_command_state(
        pp::renderer::gl::OpenGlConvertCommandStateDispatch {
            .enable = pp::legacy::ui_gl::enable_opengl_state,
            .disable = pp::legacy::ui_gl::disable_opengl_state,
            .blend_func = pp::legacy::ui_gl::set_opengl_blend_func,
            .blend_equation = pp::legacy::ui_gl::set_opengl_blend_equation,
        });
    if (!status.ok())
        LOG("OpenGL convert command state failed: %s", status.message);
}

class LegacyCommandConvertServices final : public pp::app::CommandConvertServices {
public:
    void apply_renderer_state() override
    {
        apply_convert_command_state();
    }

    void create_canvas(int canvas_resolution) override
    {
        command_canvas = new Canvas;
        command_canvas->create(canvas_resolution, canvas_resolution);
    }

    void open_project(std::string_view project_path) override
    {
        if (command_canvas)
            command_canvas->project_open_thread(std::string(project_path));
    }

    void export_equirectangular(std::string_view output_path) override
    {
        if (command_canvas)
            command_canvas->export_equirectangular_thread(std::string(output_path));
    }

private:
    Canvas* command_canvas = nullptr;
};

}

void App::cmd_convert(std::string pano_path, std::string out_path)
{
    const auto plan = pp::app::plan_command_convert(
        pano_path,
        out_path,
        default_canvas_resolution());
    if (!plan) {
        LOG("Convert command rejected: %s", plan.status().message);
        return;
    }

    LegacyCommandConvertServices services;
    const auto status = pp::app::execute_command_convert_plan(plan.value(), services);
    if (!status.ok())
        LOG("Convert command failed: %s", status.message);
}
