using Hotline.Snapshot;
using Hotline.Snapshot.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Dependency;
using XF.Domain.Repository.Events;

namespace Hotline.Orders.DatabaseEventHandler;
public class OrderSnapshotEventHandler : IUpdateDatabaseEvent<OrderSnapshot>, IScopeDependency
{
    private readonly IIndustryLogRepository _industryLogRepository;
    private readonly IOrderSnapshotRepository _orderSnapshotRepository;
    private readonly IOrderRepository _orderRepository;

    public OrderSnapshotEventHandler(IIndustryLogRepository industryLogRepository, IOrderSnapshotRepository orderSnapshotRepository, IOrderRepository orderRepository)
    {
        _industryLogRepository = industryLogRepository;
        _orderSnapshotRepository = orderSnapshotRepository;
        _orderRepository = orderRepository;
    }

    public void OnInserted(OrderSnapshot entity)
    {
    }

    public void OnUpdated(OrderSnapshot entity)
    {
    }

    public void OnUpdating(OrderSnapshot entity)
    {
        var industry = _orderSnapshotRepository.Queryable()
            .Where(m => m.Id == entity.Id)
            .Select(m => m.IndustryName)
            .First();
        if (entity.IndustryName == industry) return;

        var order = _orderRepository.Queryable()
            .Where(m => m.Id == entity.Id)
            .Select(m => new { m.No, m.Title })
            .First();
        if (order is null) return;
        var entityLog = new IndustryLog
        {
            IndustryName = entity.IndustryName,
            OldIndustryName = industry,
            CreationTime = DateTime.Now,
            OrderId = entity.Id,
            Title = order.Title,
            No = order.No
        };
        _industryLogRepository.AddAsync(entityLog).GetAwaiter().GetResult();

    }
}
