' IDispatch COM automation via OBJECT CALL via DECLARE
#COMPILE EXE
#DIM ALL

DECLARE FUNCTION CoInitialize LIB "OLE32.DLL" (BYVAL pvReserved AS LONG) AS LONG
DECLARE FUNCTION CoUninitialize LIB "OLE32.DLL" () AS LONG
DECLARE FUNCTION CoCreateInstance LIB "OLE32.DLL" (BYREF rclsid As Byte, BYVAL pUnkOuter AS LONG, BYVAL dwClsContext AS LONG, BYREF riid As Byte, BYREF ppv AS LONG) AS LONG

SUB PrintDispatchCall(BYVAL objName AS STRING, BYVAL method AS STRING, BYVAL arg1 AS STRING, BYVAL arg2 AS STRING)
    PRINT "Object: "; objName
    PRINT "Method: "; method
    PRINT "Args: '"; arg1; "', '"; arg2; "'"
    PRINT "Steps:"
    PRINT "  1. CLSIDFromProgID('"; objName; "') -> CLSID"
    PRINT "  2. CoCreateInstance -> IUnknown"
    PRINT "  3. QueryInterface(IID_IDispatch) -> IDispatch"
    PRINT "  4. GetIDsOfNames('"; method; "') -> dispID"
    PRINT "  5. Invoke(dispID, args) -> result"
END SUB

SUB ExcelDemo()
    PRINT "Excel Automation:"
    PrintDispatchCall("Excel.Application", "Workbooks.Open", "C:\report.xlsx", "")
    PRINT ""
    PrintDispatchCall("Excel.Application", "Visible", "True", "")
    PRINT ""
    PrintDispatchCall("Excel.ActiveWorkbook", "SaveAs", "C:\output.xlsx", "xlWorkbookDefault")
END SUB

SUB WordDemo()
    PRINT ""
    PRINT "Word Automation:"
    PrintDispatchCall("Word.Application", "Documents.Add", "", "")
    PrintDispatchCall("Word.Selection", "TypeText", "Hello from PBXB64!", "")
    PrintDispatchCall("Word.Application", "Visible", "True", "")
END SUB

SUB PropertyAccessSim()
    PRINT ""
    PRINT "Property Get/Set via IDispatch:"
    PRINT "  Get: IDispatch::Invoke(dispID, DISPATCH_PROPERTYGET)"
    PRINT "  Set: IDispatch::Invoke(dispID, DISPATCH_PROPERTYPUT)"
    PRINT ""
    PRINT "Example: Excel.Application.Visible"
    PRINT "  GET: returns current state (True/False)"
    PRINT "  PUT: sets to new value"
END SUB

SUB COMInitSequence()
    PRINT ""
    PRINT "COM initialization:"
    PRINT "  1. CoInitialize(0) -> S_OK"
    PRINT "  2. CoCreateInstance(CLSID, ..., IID) -> ppv"
    PRINT "  3. Use object"
    PRINT "  4. CoUninitialize()"
END SUB

SUB HRESULTDescriptions()
    PRINT ""
    PRINT "Common HRESULT values:"
    PRINT "  S_OK = 0: Success"
    PRINT "  S_FALSE = 1: Success (different)"
    PRINT "  E_NOINTERFACE = -2147467262: No interface"
    PRINT "  E_FAIL = -2147467259: Unspecified error"
    PRINT "  DISP_E_MEMBERNOTFOUND: Method not found"
END SUB

FUNCTION PBMAIN() AS LONG
    PRINT "=== COM Dispatch Demo ==="
    PRINT "OLE32: CoCreateInstance, IDispatch via DECLARE"
    ExcelDemo()
    WordDemo()
    PropertyAccessSim()
    COMInitSequence()
    HRESULTDescriptions()
    PRINT "=== End COM Dispatch ==="
    FUNCTION = 0
END FUNCTION
