using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XF.Domain.Repository.Events;
public class DatabaseEventDispatcher
{
    private readonly IServiceProvider _serviceProvider;

    public DatabaseEventDispatcher(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void Dispatch<TEntity>(TEntity entity, DataFilterType operationType, bool befor) where TEntity : new()
    {
        var targetInterface = typeof(IUpdateDatabaseEvent<>).MakeGenericType(entity.GetType());
        var handler = _serviceProvider.GetService(targetInterface);
        if (handler == null) return;

        switch (operationType)
        {
            case DataFilterType.UpdateByObject:
                if (befor)
                    targetInterface?.GetMethod("OnUpdating")?.Invoke(handler, [entity]);
                else
                    targetInterface?.GetMethod("OnUpdated")?.Invoke(handler,[entity]);
                break;
            case DataFilterType.InsertByObject:
                targetInterface?.GetMethod("OnInserted")?.Invoke(handler, [entity]);
                break;
        }
    }
  }
