using System;
using System.Runtime.InteropServices;

namespace ZB.MOM.WW.MxGateway.Worker.Sta;

public sealed class StaComApartmentInitializer : IStaComApartmentInitializer
{
    private const uint CoInitializeApartmentThreaded = 0x2;
    private const int SOk = 0;
    private const int SFalse = 1;

    /// <inheritdoc />
    public void Initialize()
    {
        int hresult = CoInitializeEx(IntPtr.Zero, CoInitializeApartmentThreaded);
        if (hresult != SOk && hresult != SFalse)
        {
            throw new COMException("Failed to initialize the worker STA COM apartment.", hresult);
        }
    }

    /// <inheritdoc />
    public void Uninitialize()
    {
        CoUninitialize();
    }

    [DllImport("ole32.dll")]
    private static extern int CoInitializeEx(IntPtr reserved, uint coInit);

    [DllImport("ole32.dll")]
    private static extern void CoUninitialize();
}
