#include "Dialogs.hpp"

#include <shobjidl.h>
#include <iostream>

namespace GModTeach {
namespace Platform {

namespace {

struct ScopedCoInit {
    HRESULT hr;
    ScopedCoInit() {
        hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    }
    ~ScopedCoInit() {
        if (SUCCEEDED(hr)) {
            CoUninitialize();
        }
    }
};

} 

std::optional<std::filesystem::path> Dialogs::OpenFolderDialog(
    const std::wstring& title,
    HWND parent
) {
    ScopedCoInit comScope;

    IFileOpenDialog* pDialog = nullptr;
    HRESULT hr = CoCreateInstance(
        CLSID_FileOpenDialog,
        nullptr,
        CLSCTX_INPROC_SERVER,
        IID_PPV_ARGS(&pDialog)
    );

    if (FAILED(hr) || !pDialog) {
        std::cerr << "[ERROR] CoCreateInstance for FileOpenDialog failed: 0x" << std::hex << hr << "\n";
        return std::nullopt;
    }

    DWORD options = 0;
    pDialog->GetOptions(&options);
    pDialog->SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
    pDialog->SetTitle(title.c_str());

    hr = pDialog->Show(parent);
    if (FAILED(hr)) {
        pDialog->Release();
        return std::nullopt;
    }

    IShellItem* pItem = nullptr;
    hr = pDialog->GetResult(&pItem);
    if (FAILED(hr) || !pItem) {
        pDialog->Release();
        return std::nullopt;
    }

    PWSTR path = nullptr;
    hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &path);
    if (FAILED(hr) || !path) {
        pItem->Release();
        pDialog->Release();
        return std::nullopt;
    }

    std::filesystem::path selectedPath(path);

    CoTaskMemFree(path);
    pItem->Release();
    pDialog->Release();

    return selectedPath;
}

void Dialogs::ShowInfoDialog(
    const std::string& title,
    const std::string& message,
    HWND parent
) {
    MessageBoxA(parent, message.c_str(), title.c_str(), MB_OK | MB_ICONINFORMATION);
}

void Dialogs::ShowErrorDialog(
    const std::string& title,
    const std::string& message,
    HWND parent
) {
    MessageBoxA(parent, message.c_str(), title.c_str(), MB_OK | MB_ICONERROR);
}

} 
} 
