// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.InteropServices;
using Windows.Win32;
using Windows.Win32.System.Com;
using WinRT;

namespace WindowsPackageManager.Interop;

public class WindowsPackageManagerStandardFactory : WindowsPackageManagerFactory
{
    public WindowsPackageManagerStandardFactory(ClsidContext clsidContext = ClsidContext.Prod)
        : base(clsidContext)
    {
    }

    protected override T CreateInstance<T>(Guid clsid, Guid iid)
    {
        var pUnknown = IntPtr.Zero;
        unsafe
        {
            try
            {
                var hr = PInvoke.CoCreateInstance(clsid, null, CLSCTX.CLSCTX_ALL, iid, out var result);
                Marshal.ThrowExceptionForHR(hr);

                pUnknown = new IntPtr(result);

                return MarshalGeneric<T>.FromAbi(pUnknown);
            }
            finally
            {
                // CoCreateInstance and FromAbi both AddRef on the native object.
                // Release once to prevent memory leak.
                if (pUnknown != IntPtr.Zero)
                {
                    Marshal.Release(pUnknown);
                }
            }
        }
    }
}
