#pragma once

#include "app_core/app_status.h"
#include "foundation/result.h"

#include <string>
#include <string_view>

namespace pp::app {

struct DocumentResizeDialogState {
    int current_resolution = 0;
    std::string current_resolution_text;
    int current_resolution_index = 0;
};

struct DocumentResizePlan {
    int resolution = 0;
    int width = 0;
    int height = 0;
    bool clears_history = false;
};

class DocumentResizeServices {
public:
    virtual ~DocumentResizeServices() = default;

    virtual void resize_document(int width, int height) = 0;
    virtual void update_title() = 0;
    virtual void clear_history() = 0;
};

[[nodiscard]] inline DocumentResizeDialogState make_document_resize_dialog_state(
    int current_resolution)
{
    const auto label = document_resolution_label(current_resolution);
    const auto index = document_resolution_to_index(current_resolution);
    std::string text = "Current: ";
    text.append(label ? std::string_view(label.value()) : std::string_view("unknown"));

    return {
        current_resolution,
        text,
        index ? static_cast<int>(index.value()) : static_cast<int>(document_resolution_values.size()),
    };
}

[[nodiscard]] inline pp::foundation::Result<DocumentResizePlan> plan_document_resize(
    int selected_resolution_index)
{
    const auto resolution = display_resolution_from_index(selected_resolution_index);
    if (!resolution) {
        return pp::foundation::Result<DocumentResizePlan>::failure(resolution.status());
    }

    const auto value = resolution.value();
    return pp::foundation::Result<DocumentResizePlan>::success(
        DocumentResizePlan {
            value,
            value,
            value,
            true,
        });
}

[[nodiscard]] inline pp::foundation::Status execute_document_resize_plan(
    const DocumentResizePlan& plan,
    DocumentResizeServices& services)
{
    if (plan.width <= 0 || plan.height <= 0) {
        return pp::foundation::Status::out_of_range("resize dimensions must be positive");
    }

    services.resize_document(plan.width, plan.height);
    services.update_title();
    if (plan.clears_history) {
        services.clear_history();
    }
    return pp::foundation::Status::success();
}

}
