import ctypes
from ctypes import wintypes
import os

# Windows API Constants
OFN_FILEMUSTEXIST = 0x00001000
OFN_PATHMUSTEXIST = 0x00000800

class OPENFILENAME(ctypes.Structure):
    _fields_ = [
        ("lStructSize", wintypes.DWORD),
        ("hwndOwner", wintypes.HWND),
        ("hInstance", wintypes.HINSTANCE),
        ("lpstrFilter", wintypes.LPCWSTR),
        ("lpstrCustomFilter", wintypes.LPWSTR),
        ("nMaxCustFilter", wintypes.DWORD),
        ("nFilterIndex", wintypes.DWORD),
        ("lpstrFile", wintypes.LPWSTR),
        ("nMaxFile", wintypes.DWORD),
        ("lpstrFileTitle", wintypes.LPWSTR),
        ("nMaxFileTitle", wintypes.DWORD),
        ("lpstrInitialDir", wintypes.LPCWSTR),
        ("lpstrTitle", wintypes.LPCWSTR),
        ("Flags", wintypes.DWORD),
        ("nFileOffset", wintypes.WORD),
        ("nFileExtension", wintypes.WORD),
        ("lpstrDefExt", wintypes.LPCWSTR),
        ("lCustData", wintypes.LPARAM),
        ("lpfnHook", ctypes.c_void_p),
        ("lpTemplateName", wintypes.LPCWSTR),
        ("pvReserved", ctypes.c_void_p),
        ("dwReserved", wintypes.DWORD),
        ("FlagsEx", wintypes.DWORD),
    ]

def get_open_file_native(title="Chọn tệp PDF", initial_dir=None):
    """
    Mở hộp thoại chọn tệp chuẩn của Windows bằng comdlg32.dll.
    """
    comdlg32 = ctypes.WinDLL('comdlg32.dll', use_last_error=True)
    
    # Định nghĩa bộ lọc: "PDF Files\0*.pdf\0All Files\0*.*\0\0"
    filter_str = "PDF Files\0*.pdf\0All Files\0*.*\0\0"
    
    # Buffer để lưu đường dẫn tệp đã chọn
    file_buffer = ctypes.create_unicode_buffer(1024)
    
    ofn = OPENFILENAME()
    ofn.lStructSize = ctypes.sizeof(OPENFILENAME)
    ofn.lpstrFilter = filter_str
    ofn.lpstrFile = ctypes.cast(file_buffer, wintypes.LPWSTR)
    ofn.nMaxFile = len(file_buffer)
    ofn.lpstrTitle = title
    ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST
    
    if initial_dir:
        ofn.lpstrInitialDir = initial_dir

    if comdlg32.GetOpenFileNameW(ctypes.byref(ofn)):
        return file_buffer.value
    return None

if __name__ == "__main__":
    path = get_open_file_native()
    if path:
        print(f"File selected: {path}")
    else:
        print("No file selected.")
