#include "FileDialog.h"
#include "Logger.h"
#include <commdlg.h>
#include <vector>

namespace UsdLayerManager {

std::string FileDialog::OpenFile(const char* filter, const char* title, HWND owner) {
    std::vector<char> filename(MAX_PATH_LENGTH, 0);
    
    OPENFILENAMEA ofn = {};
    ofn.lStructSize = sizeof(OPENFILENAMEA);
    ofn.hwndOwner = owner;
    ofn.lpstrFilter = filter;
    ofn.lpstrFile = filename.data();
    ofn.nMaxFile = MAX_PATH_LENGTH;
    ofn.lpstrTitle = title;
    ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
    
    if (GetOpenFileNameA(&ofn)) {
        return std::string(filename.data());
    }
    
    // User cancelled or error occurred
    DWORD error = CommDlgExtendedError();
    if (error != 0) {
        LOG_ERROR("File dialog error code: " + std::to_string(error));
    }
    
    return "";
}

std::string FileDialog::SaveFile(const char* filter, const char* title, const char* defaultExt, HWND owner) {
    std::vector<char> filename(MAX_PATH_LENGTH, 0);
    
    OPENFILENAMEA ofn = {};
    ofn.lStructSize = sizeof(OPENFILENAMEA);
    ofn.hwndOwner = owner;
    ofn.lpstrFilter = filter;
    ofn.lpstrFile = filename.data();
    ofn.nMaxFile = MAX_PATH_LENGTH;
    ofn.lpstrTitle = title;
    ofn.lpstrDefExt = defaultExt;
    ofn.Flags = OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
    
    if (GetSaveFileNameA(&ofn)) {
        return std::string(filename.data());
    }
    
    // User cancelled or error occurred
    DWORD error = CommDlgExtendedError();
    if (error != 0) {
        LOG_ERROR("File dialog error code: " + std::to_string(error));
    }
    
    return "";
}

} // namespace UsdLayerManager
