using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

[Guid("f5b13fa4-8472-4f82-8a47-515b879006ba"), ComVisible(true), ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(INotificationActivationCallback))]
public class NotificationActivator : NotificationActivatorBase
{ }

[Guid("1EC6017A-77C7-44DB-AF97-22452FA26652"), ComVisible(true), ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(INotificationActivationCallback))]
public class NotificationActivatorBase : INotificationActivationCallback
{
    public void Activate(string appUserModelId, string invokedArgs, NOTIFICATION_USER_INPUT_DATA[] data, uint count)
    {
        _action?.Invoke(invokedArgs, data?.Take((int)count).ToDictionary(x => x.Key, x => x.Value));
    }

    private static int? _cookie;
    private static Action<string, Dictionary<string, string>> _action;

    public static void RegisterComType(Type activatorType, Action<string, Dictionary<string, string>> action)
    {
        _cookie = new RegistrationServices().RegisterTypeForComClients(
            activatorType,
            RegistrationClassContext.LocalServer,
            RegistrationConnectionType.MultipleUse);

        _action = action;
    }

    public static void UnregisterComType()
    {
        if (!_cookie.HasValue)
            return;

        new RegistrationServices().UnregisterTypeForComClients(_cookie.Value);
        _cookie = null;
        _action = null;
    }
}