using Dapper;
using Lada.Framework.Data.Domains.Cms;
using Lada.Framework.Data.Repositories;
using Lada.Framework.DTO.SmartTable;
using Lada.Framework.Infrastructures.Helpers;
using ladaexpress.vn.Infrastructures.DTO;
using ladaexpress.vn.Infrastructures.DTO.Models.Post.Detail;
using ladaexpress.vn.Infrastructures.DTO.Models.Post.Index;
using ladaexpress.vn.Infrastructures.DTO.Models.Post.Index.Childs;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Text.RegularExpressions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace ladaexpress.vn.Infrastructures.Services

{
    public interface IPostService
    {
        /// <summary>
        /// Tìm kiếm bài viết
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        Task<PostIndexModel> PreparePostIndex();

        Task<PostDetailModel> PreparePostDetail(int id);

        /// <summary>
        /// Tạo / cập nhật bài viết
        /// </summary>
        /// <param name="model"></param>
        /// <param name="updateBy"></param>
        /// <param name="updateByUserName"></param>
        /// <returns></returns>
        //Task<PostResult> CreateOrUpdate(PostModel model);

        /// <summary>
        /// Lấy thông tin bài viết qua Id
        /// </summary>
        /// <param name="postId"></param>
        /// <returns></returns>
        //Task<PostModel> GetById(int postId);

        /// <summary>
        /// Xóa bài viết
        /// </summary>
        /// <param name="postId"></param>
        /// <returns></returns>
        //Task<BaseResult> Delete(int postId);



    }


    public class PostService : IPostService
    {
        private readonly IRepository<Post> _postRepository;
        private readonly IRepository<Category> _categoryRepository;
        private readonly IRepository<UrlRecord> _urlRecordRepository;
        private readonly IDbConnection _dbConnection;


        public PostService(IRepository<Post> postRepository, IRepository<UrlRecord> urlRecordRepository,
            IRepository<Category> categoryRepository, IDbConnection dbConnection)
        {
            _postRepository = postRepository;
            _urlRecordRepository = urlRecordRepository;
            _categoryRepository = categoryRepository;
            _dbConnection = dbConnection;
        }

        public async Task<PostIndexModel> PreparePostIndex()
        {
            var model = new PostIndexModel();
            var currentTime = DateTimeHelper.CurrentTime();
            var newTime = currentTime.AddDays(-3);//Những bài viết có ngày xuất bản 3 ngày trở về đây được coi là bài viết mới
            var query = _postRepository.Query().Where(p => p.ValidFrom <= currentTime
                                                            && p.Status == PostStatus.Published
                                                            && p.Visibility == PostVisibility.Public);

            model.FeaturedPosts = await PrepareFeaturedPosts();
            model.NewPosts = await PrepareNewPosts();


            return model;

        }

        #region PostIndex Sections

        public async Task<List<PostItem>> PrepareNewPosts()
        {
            var posts = new List<PostItem>();
            try
            {
                posts = (await _dbConnection.QueryAsync<PostItem>("PostIndex_GetNewPosts", commandType: CommandType.StoredProcedure)).ToList();
            }
            catch (Exception)
            {
            }
            return posts;
        }



        public async Task<List<PostItem>> PrepareFeaturedPosts()
        {
            var currentTime = DateTimeHelper.CurrentTime();
            var query = _postRepository.Query().Where(p => p.ValidFrom <= currentTime
                                                            && p.Status == PostStatus.Published
                                                            && p.Visibility == PostVisibility.Public);

            return await query.Where(p => p.IsFeatured)
                                            .OrderByDescending(p => p.UpdatedTime).Take(5)
                                            .Include(p => p.UrlRecord).Select(p => p.ToItem()).ToListAsync();
        }


        #endregion


        public async Task<PostDetailModel> PreparePostDetail(int id)
        {
            var model = new PostDetailModel();
            var currentTime = DateTimeHelper.CurrentTime();
            var post = await _postRepository.Query().Include(p => p.UrlRecord)
                .Include(p => p.PostTags!).ThenInclude(pt => pt.Tag!).ThenInclude(t => t.UrlRecord!)
                .FirstOrDefaultAsync(p => p.Id == id
                                    && p.ValidFrom <= currentTime
                                    && p.Status == PostStatus.Published
                                    && p.Visibility == PostVisibility.Public);
            if (post != null && post.Id > 0)
            {
                model = post.ToDetailModel();
                if (post.PostTags != null && post.PostTags.Any())
                {
                    foreach (var postTag in post.PostTags)
                    {
                        if (postTag.Tag != null && postTag.Tag.Id > 0)
                        {
                            var tagSlug = "";
                            if (postTag.Tag.UrlRecord != null)
                            {
                                tagSlug = postTag.Tag.UrlRecord.Slug;
                            }
                            model.Tags.Add(new PostTagItem() { Id = postTag.Tag.Id, Name = postTag.Tag.Name, Slug = tagSlug });
                        }
                    }
                }


                if (!string.IsNullOrEmpty(model.Description))
                {
                    var plaintext = Regex.Replace(model.Description, "<(.|\n)*?>", "").Trim();
                    char[] delimiters = new char[] { ' ', '\r', '\n' };
                    var wordCount = plaintext.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).Length;
                    int readingSpeed = 200;
                    int estimatedReadingTime = (wordCount * 60) / readingSpeed;
                    // Chuyển thời gian từ giây thành phút và giây
                    int minutes = estimatedReadingTime / 60;
                }
                //if (model.Tags.Any())
                //{
                //    var tagIds = model.Tags.Select(t => t.Id).ToList();
                //    var tagUrlRecords = await _urlRecordRepository.Query().Where(u => u.TagId.HasValue && tagIds.Contains(u.TagId.Value)).ToListAsync();
                //    if (tagUrlRecords.Any())
                //    {
                //        foreach (var item in model.Tags)
                //        {
                //            var urlRecord = tagUrlRecords.FirstOrDefault(u => u.TagId == item.Id);
                //            if (urlRecord != null && urlRecord.Id > 0)
                //            {
                //                item.Slug = urlRecord.Slug;
                //            }
                //        }
                //    }
                //}

            }
            return model;
        }



    }
}
