using Microsoft.AspNetCore.Mvc;
using Nop.Web.Framework.Components;
using Nop.Web.Areas.Admin.Factories;
using Nop.Web.Areas.Admin.Models.Blogs;
using System.Collections.Generic;
using Nop.Services.Media;
using Nop.Services.Blogs;
using Nop.Web.Areas.Admin.Infrastructure.Mapper.Extensions;
using Nop.Web.Models.Media;

namespace Nop.Web.Components
{
    public class HomepageBlogB2CViewComponent : NopViewComponent
    {
        private readonly IBlogModelFactory _blogModelFactory;
        private readonly IPictureService _pictureService;
        private readonly IBlogsB2CService _blogsB2CService;

        public HomepageBlogB2CViewComponent(IBlogModelFactory blogModelFactory,
            IPictureService pictureService,
            IBlogsB2CService blogsB2CService)
        {
            _blogModelFactory = blogModelFactory;
            _pictureService = pictureService;
            _blogsB2CService = blogsB2CService;
        }

        public IViewComponentResult Invoke()
        {
            var searchModel = new BlogPostSearchModel
            {
                Length = int.MaxValue,

            };

            var model = _blogModelFactory.PrepareBlogPostListModel(searchModel);
            var lst = new List<BlogPostModel>(model.Data);

            lst.ForEach(x =>
            {
                SetPictureModel(x);
            });

            return View(lst);
        }

        private void SetPictureModel(BlogPostModel blogPostModel)
        {
            var blogPostPicture = _blogsB2CService.GetBlogPostPictureById(blogPostModel.Id);
            if(blogPostPicture !=null && blogPostPicture.PictureId > 0)
            {
                var picture = _pictureService.GetPictureById(blogPostPicture.PictureId);
                blogPostModel.PictureImageUrl = _pictureService.GetPictureUrl(picture);
            }
        }
    }
}
