using Hotline.Caching.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hotline.FlowEngine.WorkflowModules;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Caching.Services
{
    public class WfModuleCacheManager : IWfModuleCacheManager, IScopeDependency
    {
        private readonly ITypedCache<WorkflowModule> _cacheWfModule;
        private readonly IRepository<WorkflowModule> _wfModuleRepository;

        public WfModuleCacheManager(ITypedCache<WorkflowModule> cacheWfModule, IRepository<WorkflowModule> wfModuleRepository)
        {
            _cacheWfModule = cacheWfModule;
            _wfModuleRepository = wfModuleRepository;
        }

        public Task<WorkflowModule?> GetWorkflowModuleAsync(string code, CancellationToken cancellationToken)
        {
            return _cacheWfModule.GetOrSetAsync(code, k =>
            {
                var module = _wfModuleRepository.Queryable()
                    .Includes(d => d.Definition)
                    .First(d => d.Code == code);
                if (module == null)
                    throw new UserFriendlyException("无效流程模板编号");
                return module;
            }, TimeSpan.FromDays(7), cancellationToken);
        }

        public Task RemoveWorkflowModuleAsync(string code, CancellationToken cancellationToken) => 
            _cacheWfModule.RemoveAsync(code, cancellationToken);
    }
}
