#include "pch.h"

#include "legacy_recording_services.h"

#include "app.h"
#include "canvas.h"
#include "node_progress_bar.h"

namespace pp::panopainter {
namespace {

class LegacyRecordingServices final : public pp::app::RecordingServices {
public:
    explicit LegacyRecordingServices(App& app) noexcept
        : app_(app)
    {
    }

    void start_thread() override
    {
        app_.update_rec_frames();
        app_.rec_thread = std::thread(&App::rec_loop, &app_);
    }

    void stop_thread() override
    {
        app_.rec_running = false;
        app_.rec_cv.notify_all();
        if (app_.rec_thread.joinable())
            app_.rec_thread.join();
        app_.update_rec_frames();
    }

    void delete_recorded_files() override
    {
        app_.clear_platform_recorded_files(app_.rec_path);
    }

    void set_frame_count(int frame_count) override
    {
        app_.rec_count = frame_count;
    }

    void update_frame_label() override
    {
        app_.update_rec_frames();
    }

    void begin_export(int progress_total) override
    {
        progress_ = app_.layout[app_.main_id]->add_child<NodeProgressBar>();
        progress_->m_progress->SetWidthP(0);
        progress_->m_title->set_text("Exporting MP4 movie");
        progress_->m_total = progress_total;
        progress_->m_count = 0;
    }

    void write_mp4(std::string_view path) override
    {
        Canvas::I->m_encoder->write_mp4(std::string(path));
    }

    void end_export() override
    {
        if (progress_)
            progress_->destroy();
        progress_ = nullptr;
    }

private:
    App& app_;
    NodeProgressBar* progress_ = nullptr;
};

} // namespace

pp::foundation::Status execute_legacy_recording_start_action(
    App& app,
    pp::app::RecordingStartAction action)
{
    LegacyRecordingServices services(app);
    return pp::app::execute_recording_start_action(action, services);
}

pp::foundation::Status execute_legacy_recording_stop_action(
    App& app,
    pp::app::RecordingStopAction action)
{
    LegacyRecordingServices services(app);
    return pp::app::execute_recording_stop_action(action, services);
}

pp::foundation::Status execute_legacy_recording_clear_plan(
    App& app,
    const pp::app::RecordingClearPlan& plan)
{
    LegacyRecordingServices services(app);
    return pp::app::execute_recording_clear_plan(plan, services);
}

pp::foundation::Status execute_legacy_recording_export_plan(
    App& app,
    const pp::app::RecordingExportPlan& plan,
    std::string_view path)
{
    LegacyRecordingServices services(app);
    return pp::app::execute_recording_export_plan(plan, services, path);
}

} // namespace pp::panopainter
