#include "pch.h"

#include "legacy_cloud_services.h"

#include "app.h"
#include "canvas.h"
#include "legacy_app_dialog_services.h"
#include "legacy_canvas_view_services.h"
#include "legacy_ui_overlay_services.h"
#include "node_dialog_cloud.h"
#include "node_progress_bar.h"
#include "util.h"

namespace pp::panopainter {
namespace {

class LegacyCloudServices final : public pp::app::CloudServices {
public:
    explicit LegacyCloudServices(App& app) noexcept
        : app_(app)
    {
    }

    void show_save_required_warning() override
    {
        const auto plan = pp::app::plan_cloud_save_required_prompt();
        app_.message_box(plan.title, plan.message, plan.show_cancel);
    }

    void prompt_publish(bool save_before_upload) override
    {
        auto* app = &app_;
        auto upload_thread = [app, save_before_upload] {
            BT_SetTerminate();

            if (save_before_upload)
            {
                Canvas::I->project_save_thread(app->doc_path, true);
            }

            const auto progress_plan = pp::app::plan_cloud_upload_progress_dialog();
            auto pb = app->show_progress(progress_plan.title, progress_plan.total);

            app->upload(app->doc_path, app->doc_filename, [pb](float p) {
                pb->set_progress(p);
            });

            pp::panopainter::close_legacy_dialog_node(*pb);
            const auto success_plan = pp::app::plan_cloud_upload_success_prompt();
            app->message_box(success_plan.title, success_plan.message, success_plan.show_cancel);
        };

        const auto prompt_plan = pp::app::plan_cloud_publish_prompt();
        auto m = app_.message_box(prompt_plan.title, prompt_plan.message, prompt_plan.show_cancel);
        m->btn_ok->on_click = [m, upload_thread](Node*) {
            std::thread(upload_thread).detach();
            pp::panopainter::close_legacy_dialog_node(*m);
        };
        m->btn_cancel->on_click = [m](Node*) {
            pp::panopainter::close_legacy_dialog_node(*m);
        };
    }

    void begin_bulk_upload(int progress_total, bool show_progress) override
    {
        bulk_progress_.reset();
        if (show_progress) {
            const auto progress_plan = pp::app::plan_cloud_bulk_upload_progress_dialog(progress_total);
            bulk_progress_ = app_.show_progress(progress_plan.title, progress_plan.total);
        }
    }

    void upload_all_bulk_files() override
    {
        auto names = Asset::list_files(app_.data_path, ".*\\.ppi");
        [[maybe_unused]] gl_state gl;
        for (const auto& n : names)
        {
            std::string path = app_.data_path + "/" + n;
            app_.upload(path);

            if (bulk_progress_) {
                bulk_progress_->increment();
            }
        }
    }

    void end_bulk_upload() override
    {
        if (bulk_progress_) {
            pp::panopainter::close_legacy_dialog_node(*bulk_progress_);
        }
        bulk_progress_.reset();
    }

    void show_browser() override
    {
        auto dialog = std::make_shared<NodeDialogCloud>();
        dialog->set_manager(&app_.layout);
        dialog->init();
        dialog->create();
        dialog->loaded();

        app_.layout[app_.main_id]->add_child(dialog);

        auto* app = &app_;
        dialog->btn_ok->on_click = [app, dialog](Node*) {
            const auto selection_plan = pp::app::plan_cloud_download_selection(dialog->selected_file);
            const auto status = execute_legacy_cloud_download_selection_action(*app, selection_plan, *dialog);
            if (!status.ok())
                LOG("Cloud download selection action failed: %s", status.message);
        };
    }

    void start_download(const pp::app::CloudDownloadRequest& request) override
    {
        auto* app = &app_;
        std::thread([app, request] {
            BT_SetTerminate();

            auto m = pp::panopainter::create_legacy_app_message_dialog(
                *app,
                pp::app::plan_cloud_download_progress_prompt());
            std::string url = "https://panopainter.com/cloud/cloud-dwl.php?file=" + request.selected_file;
            app->download(url, request.selected_path, [m](float p) {
                const auto progress = pp::app::format_cloud_download_progress_message(p);
                m->m_message->set_text(progress.c_str());
            });

            const auto reset_status = execute_legacy_canvas_camera_reset(*app);
            if (!reset_status.ok())
                LOG("Cloud download camera reset failed: %s", reset_status.message);
            app->layers->clear();

            app->canvas->m_canvas->project_open_thread(request.selected_path);

            app->doc_name = request.selected_name;
            app->title_update();
            for (auto& l : app->canvas->m_canvas->m_layers)
                app->layers->add_layer(l->m_name.c_str(), false);
            ActionManager::clear();
            pp::panopainter::close_legacy_dialog_node(*m);
        }).detach();
    }

private:
    App& app_;
    std::shared_ptr<NodeProgressBar> bulk_progress_;
};

} // namespace

pp::foundation::Status execute_legacy_cloud_upload_plan(
    App& app,
    const pp::app::CloudUploadPlan& plan)
{
    LegacyCloudServices services(app);
    return pp::app::execute_cloud_upload_plan(plan, services);
}

pp::foundation::Status execute_legacy_cloud_bulk_upload_plan(
    App& app,
    const pp::app::CloudBulkUploadPlan& plan)
{
    LegacyCloudServices services(app);
    return pp::app::execute_cloud_bulk_upload_plan(plan, services);
}

pp::foundation::Status execute_legacy_cloud_browse_action(
    App& app,
    pp::app::CloudBrowseAction action)
{
    LegacyCloudServices services(app);
    return pp::app::execute_cloud_browse_action(action, services);
}

pp::foundation::Status execute_legacy_cloud_download_selection_action(
    App& app,
    pp::app::CloudDownloadSelectionAction action,
    NodeDialogCloud& dialog)
{
    pp::app::CloudDownloadRequest request {
        .selected_file = dialog.selected_file,
        .selected_path = dialog.selected_path,
        .selected_name = dialog.selected_name,
    };
    if (action == pp::app::CloudDownloadSelectionAction::start_download) {
        pp::panopainter::close_legacy_dialog_node(dialog);
    }
    LegacyCloudServices services(app);
    return pp::app::execute_cloud_download_selection_action(action, services, request);
}

} // namespace pp::panopainter
