#include <extra2d/platform/window_module.h>
#include <extra2d/platform/backend_factory.h>
#include <extra2d/core/service_locator.h>
#include <extra2d/utils/logger.h>

#ifdef __SWITCH__
#include <switch.h>
#endif

namespace extra2d {

// 前向声明后端初始化函数
namespace platform {
#if defined(E2D_BACKEND_SDL2)
void initSDL2Backend();
#elif defined(E2D_BACKEND_GLFW)
void initGLFWBackend();
#endif
}

WindowModule::WindowModule(std::function<void(WindowCfg&)> configFn) {
    configFn(cfg_);
}

WindowModule::~WindowModule() {
    if (initialized_) {
        shutdown();
    }
}

bool WindowModule::init() {
    if (initialized_) return true;

    // 初始化后端（注册到工厂）
#if defined(E2D_BACKEND_SDL2)
    platform::initSDL2Backend();
#elif defined(E2D_BACKEND_GLFW)
    platform::initGLFWBackend();
#else
    #error "No window backend defined"
#endif

    E2D_LOG_INFO("Window backend initialized");

    E2D_LOG_INFO("Creating window with size {}x{}", cfg_.w, cfg_.h);

    // 创建窗口（使用配置的后端）
    win_ = platform::BackendFactory::createWindow(cfg_.backend);
    if (!win_) {
        E2D_LOG_ERROR("Failed to create window backend: {}", cfg_.backend);
        return false;
    }

    if (!win_->create(cfg_.title, cfg_.w, cfg_.h, cfg_.vsync)) {
        E2D_LOG_ERROR("Failed to create window");
        shutdown();
        return false;
    }

    E2D_LOG_INFO("Window created successfully");
    initialized_ = true;
    return true;
}

void WindowModule::shutdown() {
    if (!initialized_) return;
    
    if (win_) {
        win_->destroy();
        win_.reset();
    }
    
    initialized_ = false;
}

} // namespace extra2d
