using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using YGNT.QuestionLibrary.Core.Chapters.Domain;

namespace YGNT.QuestionLibrary.Core.Chapters.Event
{
    public class ChapterAutoTreePathFill : ITransientDependency
        , IAsyncEventHandler<EntityCreatingEventData<Chapter>>
        , IAsyncEventHandler<EntityDeletingEventData<Chapter>>
    {
        private readonly IChapterTreePathManager _treePathManager;
        private readonly IRepository<ChapterTreePath, long> _treePathRepository;

        public ChapterAutoTreePathFill(IChapterTreePathManager treePathManager, IRepository<ChapterTreePath, long> treePathRepository)
        {
            _treePathManager = treePathManager;
            _treePathRepository = treePathRepository;
        }

        /// <summary>
        /// 为新创建的章节添加闭包路径
        /// </summary>
        /// <param name="eventData">Event data</param>
        public async Task HandleEventAsync(EntityCreatingEventData<Chapter> eventData)
        {
            var chapter = eventData.Entity;
            await _treePathManager.CreateTreePathAsync(chapter);
        }

        /// <summary>
        ///清除删除的章节路径
        /// </summary>
        /// <param name="eventData">Event data</param>
        public async Task HandleEventAsync(EntityDeletingEventData<Chapter> eventData)
        {
            var chapter = eventData.Entity;
            var ancestor = await _treePathManager.GetAncestorAsync(chapter.Id);
            var descendant = await _treePathManager.GetDescendantAsync(chapter.Id);
            foreach (var ancestorTreePath in ancestor)
            {
                await _treePathRepository.DeleteAsync(x =>
                    x.Ancestor == ancestorTreePath.Ancestor
                    && descendant.Select(s => s.Descendant).Contains(x.Descendant));
            }
        }
    }
}